0

The text is printing in an infinite loop. Any way to avoid these?

if (eLoad) {
    File file = new File("reservation.txt");

    /** reading a file */

    try(FileInputStream fis = new FileInputStream(file)) {
        int content;
        while ((content = fis.read()) != -1) {
            // convert to char and display it  
            System.out.print((char) content);
            /**print out the result contents of the file. */
        }
    }

    catch(IOException e) {
        e.printStackTrace();
    }
}

Ooutput shown

Homeworkdue Sat Oct 10 00:00:00 PDT 2015 23:00 23
Homeworkdue Sat Oct 10 00:00:00 PDT 2015 23:00 23
Homeworkdue Sat Oct 10 00:00:00 PDT 2015 23:00 23

Tom
  • 16,842
  • 17
  • 45
  • 54
B-Y
  • 187
  • 1
  • 2
  • 12

4 Answers4

0
if (eLoad) {
    File file = new File("reservation.txt");

    /** reading a file */

    try(FileInputStream fis = new FileInputStream(file)) {
        int content;

        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
        String line = null;

        while ((line = reader.readLine()) != null) {
         // convert to char and display it  
            System.out.print(line);
            /**print out the result contents of the file. */
        }

        reader.close();
    }

    catch(IOException e) {
        e.printStackTrace();
    }
}
Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
0

Can you add

System.out.print(content); 

after

System.out.print((char) content);

I'm not very knowledgeable yet in programming but it may be because it is reading fis.read() as ASCII values, and it is either 000 or 003.

If so I would put

content = fis.read());
while (content != 3 && content != 0 || content == null) // if either not 3 and not 0 it doesn't run or if it isn't defined
{
    // do stuff
}

for the while condition

Quote: "That means, the API try to read a line of file, get -1 and returns EOF." (Looks like it doesn't return -1)

Looked at: https://superuser.com/questions/789026/eof-ascii-hex-code-in-text-files

Community
  • 1
  • 1
Riley Carney
  • 804
  • 5
  • 18
0

If you wish to read in line by line from a file you could also try

 while ((line = fis.readLine()) != null) {

The rest of the code looks fine.

Aven
  • 72
  • 10
0
if (eLoad) {
    File file = new File("reservation.txt");

    /** reading a file */

    try(FileInputStream fis = new FileInputStream(file)) {
        int content;
        while ((content = fis.read()) != 0) //JUST CHANGE THE -1 TO 0, THEN IT WORKS {
            // convert to char and display it  
            System.out.print((char) content);
        /**print out the result contents of the file. */
    }

    catch(IOException e) {
        e.printStackTrace();
    }
}
Riddhesh Sanghvi
  • 1,218
  • 1
  • 12
  • 22
B-Y
  • 187
  • 1
  • 2
  • 12