0

I got a file contains two lines:

aaaaa
bbbbb

I used these lines to read each lines:

    File f=new File("D:\\xxx.dat");
    FileReader fr = new FileReader(f);
    BufferedReader br = new BufferedReader(fr);
    String str;
    String tmpp="";
    while ((str = br.readLine()) != null) {
         if(str=="bbbbb")
         {
         System.out.print(str);
         }
    }

but I got nothing as a result.why?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Super Hornet
  • 2,839
  • 5
  • 27
  • 55

4 Answers4

6

Instead of

if(str=="bbbbb")

write

if(str.equals("bbbbb"))

String equality is a common mistake for beginners and for programmers from other languages.

gaborsch
  • 15,408
  • 6
  • 37
  • 48
1

Because you are using "==" instead of equals method.

mael
  • 2,214
  • 1
  • 19
  • 20
1

You're using == to compare the strings.

String is not a primitive type, so you should use .equals() method.

When you compare two Strings with ==, it will compare the two objects and return false because they don't point to the same String object (even though they represent the same thing).

To understand better why is that take a look at this answer https://stackoverflow.com/a/73021/2576857 , it gives a great explanation IMO.

Community
  • 1
  • 1
Doodad
  • 1,518
  • 1
  • 15
  • 20
0

It looks like your input file first line contains more than "bbbbb". Please check the value of str before If sentence and use equals method to compare strings (to compare values instead of references)

user1759572
  • 683
  • 4
  • 11