相关文章推荐
豪爽的刺猬  ·  JAVA ...·  1 月前    · 
宽容的消炎药  ·  动物福利的“3R原则”·  3 月前    · 
听话的香菜  ·  肯恩大学_百度百科·  3 月前    · 
精明的冲锋衣  ·  最后的舞动- ...·  1 年前    · 

Java中的InputStream和OutputStream是字节流读写文件的常见类,可以通过它们读取或写入二进制文件。示例代码如下:

File file = new File("example.bin");
InputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
inputStream.read(bytes);
inputStream.close();

以上代码读取了example.bin文件中的所有字节,将其存储在byte数组中,然后关闭了输入流。

  • 使用NIO读取二进制文件
  • Java的NIO(New IO)是一组提供了更高性能、更灵活的I/O操作的API。下面是一个使用NIO读取二进制文件的示例代码:

    RandomAccessFile file = new RandomAccessFile("example.bin", "r");
    FileChannel channel = file.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
    channel.read(buffer);
    buffer.flip();
    byte[] bytes = buffer.array();
    channel.close();
    file.close();
    

    以上代码使用了Java NIO的FileChannel类和ByteBuffer类。首先打开文件,然后将文件读取到ByteBuffer中,最后将ByteBuffer转换为byte数组。最后需要记得关闭文件和通道。

    以上是两种Java读取二进制文件的方式,您可以根据具体的情况选择适合自己的方法。

  •