我需要读取一个二进制文件,并将每个字节保存到字节数组中。我已经阅读了有关此主题的其他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);
}
这里是一种将文件内容读入byte
数组的方法。您只需要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
–不需要读取字节数据try
–在您发布的代码中,只有抛出Exception
或FileNotFoundException
时,您才可以看到信息。除此之外,您的代码无法处理它们或打印出任何信息。