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读取二进制文件的方式,您可以根据具体的情况选择适合自己的方法。
- 655
-
一个普普通通简简单单
Spark
Python
- 119
-
用户112986583106
Classyshark
- 129
-
vivo高启强
Android
gradle