Search code examples
javafileiobufferedreaderreadline

BufferedReader readLine() and moving through files


My question relates to how readLine() affects the current position within a file.

Let's say I have a file which has the following in it:

1

if I say

r.readLine()

then it will return "1"

If I do another

r.readLine()

It will return 'null' as there is only one line.

So - if I check the line in an while statement like so:

while (r.readLine!=null){
//Do something here

}

So this should run until it hits a null line then exit.

However, if I want to do something like:

String line;

if ((line = r.readLine()).equals("1"))
//Then do something....
else if ((line = r.readLine()).equals("2"))
//Then do something else

What happens is that obviously,by the time I get to the 2nd check, the read position has moved to the next line.

I tried doing something like this:

String line = r.readLine();
if (line=='1')
//do Something
else if (line=="2")
//do something else.

...However, with this I get some very bizarre results. If can confirm with a System.out.println command that the string 'line' is equal to say, 1 (or whatever value). but when I try to use it in an if statement, the condition never seems to trigger....

Any help here would be appreciated.


Solution

  • if (line=='1')
    //do Something
    else if (line=="2")
    //do something else.
    

    == is used for comparing references or primitive types, you can test for String equality by using equals():

    String x = "hello";
    String y = "hello";
    

    Now x == y will be true, becuase they refer to the same object in the string pool

    String x = "hello";
    String y = new String("hello");
    

    Now x == y will be false, because they are not pointing to the same object anymore, one is in the string pool, while the other is not.

    To test properly use equals(String):

    String x = "hello";
    String y = new String("hello");
    
    x.equals(y);
    

    will evaluate to true