ricedragon
ricedragon

Reputation: 173

Java file does not read from the beginning

I have a file with the following input:

ADD 1 2
SUB 2 1
MUL 2 3
DIV 4 2
QUIT

with this part of the code:

BufferedReader in = null;
String input = "";
in = new BufferedReader(fin);
while ((input = in.readLine()) != null)
{
    String line = in.readLine();    
    System.out.println(line); // for me to see the output
    out.println(line); // thats for my server
    out.flush(); // for the server
}

but it only shows:

MUL 2 3
DIV 4 2 
null

Upvotes: 0

Views: 229

Answers (2)

Zohaib
Zohaib

Reputation: 7116

Try this:

BufferedReader in = null;
String input = "";
in = new BufferedReader(fin);
while ((input = in.readLine()) != null)
{
    System.out.println(input); // for me to see the output
    out.println(input); // thats for my server
    out.flush(); // for the server
}

You were reading input from file twice, once in the while statement and once after the while statement.

Upvotes: 4

Hunter McMillen
Hunter McMillen

Reputation: 61550

You are reading a line from the file twice before you print it's contents:

(input = in.readLine())

reads a line from the file and stores it in input, then before examining input, you read another line and store it in the line variable:

String line = in.readLine(); 

Remove one of the in.readLine() calls and it should work fine.

Upvotes: 1

Related Questions