在Java中如何读取二进制文件

我们可以使用以下代码读取二进制文件:

//版本 ≥ Java SE 1.4
File file = new File("path_to_the_file");
byte[] data = new byte[(int) file.length()];
DataInputStream stream = new DataInputStream(new FileInputStream(file));
stream.readFully(data);
stream.close();

如果我们使用的是Java 7或者更高版本,则使用NIO API有更简单的方式:

//版本 ≥ Java SE 7
Path path = Paths.get("path_to_the_file");
byte [] data = Files.readAllBytes(path);
日期:2020-06-02 22:15:22 来源:oir作者:oir