2

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);
}
6
  • "save each bit as a byte" - Each bit or each byte? To read bytes from a file, use Files#readAllBytes. Commented Jan 23, 2020 at 20:27
  • If I use readAllBytes(); how do I save these into byte array? @JacobG. Commented Jan 23, 2020 at 20:30
  • The method returns a byte[]. Commented Jan 23, 2020 at 20:30
  • Try replacing your catch block to catch any exceptions, not just the two you're currently catching. This will help expose any hidden exceptions. So just catch Exception. Commented Jan 23, 2020 at 20:32
  • Do you really want to convert each byte into eight bytes of one bit each? That is what you said. Commented Jan 23, 2020 at 20:33

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.