1

I am novice in Java and I am currently working in Eclipse Kepler. I have a JSP page from where I am reading a text file which is continuously being written using a shell script.

                <b>
                    <%
                        String filePath = "/home/default/test.txt";
                        BufferedReader reader = new BufferedReader(new FileReader(filePath));
                        StringBuilder sb = new StringBuilder();
                        String line;

                        while((line = reader.readLine()) != "Success"){
                            sb.append(line+"\n");
                            out.println(sb.toString());
                        }                       
                    %>
                </b>

I need the logic to keep reading the log until it reads the final "Success" string and until it doesn't, it should not print any blank rows.

How to solve it?

Ubica
  • 1,011
  • 2
  • 8
  • 18
user728630
  • 2,025
  • 5
  • 22
  • 35

3 Answers3

2

You can achieve it this way:

while ((line = reader.readLine()) != null) {
            if (line.trim().length() == 0) {
                continue;
            }

            if (line.equals("Success")) {
                break; 
            } else {
                // perform required operation
            }

  }
Pramod Karandikar
  • 5,289
  • 7
  • 43
  • 68
1

As epoch said, "!=" is not the same as "equals()". If you are comparing Strings always use "equals()".

while(!(line = reader.readLine()).equals("Success")) {...}
Steffen
  • 341
  • 1
  • 12
0

Try this:

while(!(line = reader.readLine()).equals("Success")) {
    if (line.trim().length() != 0) {
       out.println(line+"\n");
    }
}

The line is passed directly to the out stream. The use of StringBuilder is not obvious here.

Stephan
  • 41,764
  • 65
  • 238
  • 329
  • i understand but would this code waits till it finds "Success" string coz before that i don't wanna exit the loop – user728630 Jan 23 '15 at 09:14
  • If the code finds "Success", it will exit the loop. Otherwise, it will print out any non blank line. – Stephan Jan 23 '15 at 09:16
  • @user728630 of course it would, because until it founds Success string it stays inside the loop and the line variable gets every time different value which is the next line of your text document. And to mention, it would be better to compare the line using .equals() method. – drgPP Jan 23 '15 at 09:17