将二进制文件读入字节数组

问题描述 投票:-1回答:1

我需要读取一个二进制文件,并将每个字节保存到字节数组中。我已经阅读了有关此主题的其他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);
}
java arrays binary binaryfiles readfile
1个回答
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 –不需要读取字节数据

  • [[0]与资源一起使用–它将为您关闭关联的流]
  • catchtry–在您发布的代码中,只有抛出ExceptionFileNotFoundException时,您才可以看到信息。除此之外,您的代码无法处理它们或打印出任何信息。
© www.soinside.com 2019 - 2024. All rights reserved.