我需要读取一个二进制文件并将每个字节保存到一个字节数组中。我读过有关此主题的其他 stackoverflow 帖子,但无法弄清楚为什么我的不起作用。这是我所拥有的:
String fileOne = "file1.bin";
byte[] byteArray = new byte[1000];
try{
FileInputStream fileIS = new FileInputStream(fileOne);
ObjectInputStream is = new ObjectInputStream(fileIS);
is.read(byteArray);
is.close();
for(int i =0; i < byteArray.length; i++){
System.out.println(byteArray[i]);
}
}
catch (FileNotFoundException e){
e.toString();
System.exit(0);
}
catch (IOException io){
io.toString();
System.exit(0);
}
最佳答案
这是一种将文件内容读入字节
数组的方法。 FileInputStream
就是您所需要的 - 将 ObjectInputStream
排除在外(除非您显式处理从 ObjectOutputStream<创建的数据
,但情况似乎并非如此,因为您在每个字节上调用 println()
)。
public static void main(String[] args) {
String filename = "file1.bin";
try (FileInputStream fis = new FileInputStream(filename)) {
byte[] bytes = fis.readAllBytes();
for (byte b : bytes) {
System.out.print(b);
}
} catch (Exception e) {
e.printStackTrace();
}
}
这里有一些事情:
省略使用
ObjectInputStream
– 读取字节数据不需要,并且除非数据是由相应的输出流创建的,否则不会工作。来自 Javadoc :“ObjectInputStream 反序列化之前使用 ObjectOutputStream 写入的原始数据和对象。”对资源使用
try
– 它将为您关闭关联的流catch
Exception
– 在您发布的代码中,只有抛出FileNotFoundException
或IOException
时您才会看到信息。对于其他任何事情,您的代码不会处理它们或打印出任何信息。
关于java - 将二进制文件读入字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59886496/