0

I'm starting to learn Java I/O. I have a binary File with Integer data in it and I'm trying to read from it using FileInputStream and showing the content of the file on the console. It seems I'm not making the right approach, keep getting -1 witch means end of file. Here is my code.

File f=new File("sunday.dat");
FileInputStream fis=new FileInputStream(f);

try {
    while (true) {

        number=fis.read();
        System.out.println(number);

    }
} catch (EOFException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

fis.close();
11
  • what version java are you using? Commented May 10, 2015 at 12:57
  • 1
    @DasDas Irrelevant. The operation of that code is not version-dependent. Commented May 10, 2015 at 12:59
  • while (true) {...} will try to execute its code block infinitely. If you don't have any stop condition (or break/return/throw statements) then -1 will be printed all the time after you read file content. You need to rethink your loop. BTW if you want to read data as text use Reader. Streams are for binary data. Commented May 10, 2015 at 13:00
  • yes- but depends on he java version- we can tell him whats the best way to read the file Commented May 10, 2015 at 13:01
  • @DasDas He asked why he keeps getting -1. The answer to that is not version-dependent. Commented May 10, 2015 at 13:05

1 Answer 1

2

It seems I'm not making the right approach, keep getting -1 which means end of file.

Exactly so. It means end of file. You should only get it once. You keep getting because you aren't testing for it and breaking out of the loop when you get it.

Instead you seem to be relying on catching EOFException, which is never thrown by that method.

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

1 Comment

Which approach do you suggest to solve the problem the best way? change the while loop condition? or would you approach the problem in a different way, thanks a lot!

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.