Defqon777
Defqon777

Reputation: 49

Reading a binary file into byte array

I need to read a binary file and save each byte into a byte array. I've read other stackoverflow posts on this topic, but cannot figure out why mine does not work. Here is what I have:

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);
}

Upvotes: 2

Views: 6250

Answers (1)

Kaan
Kaan

Reputation: 5794

Here's a way to read the contents of a file into a byte array. FileInputStream is all you need – leave ObjectInputStream out of it (unless you are explicitly dealing with data that was created from an ObjectOutputStream, but that doesn't seem to be the case since you are calling println() on each byte).

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();
    }
}

A few things here:

  • omit using ObjectInputStream – not needed for reading byte data, and won't work unless the data was created by the corresponding output stream. From the Javadoc: "An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. "

  • use try with resources – it will close the associated stream for you

  • catch Exception – in the code you posted, you will only see info if FileNotFoundException or IOException is thrown. For anything else, your code doesn't handle them or print out any info.

Upvotes: 3

Related Questions