user3440716
user3440716

Reputation: 649

how to compare nextline with readLine() in java?

I am new in java

i have a r.txt file like this

A
B
C

X
Y
Z

I want to know how to use readline() with "\n", so that when it starts printing it should stop at nextline as blank. As it is giving me an error. I have written like this:

while((recordData = br.readLine()) != '\n') //(at line 18 in below code)

"error: incompatible operand types string and char". But with null it does not.

Upvotes: 0

Views: 632

Answers (3)

PNS
PNS

Reputation: 19915

As long as there is input, the readLine() method will return a single line of text, without the line termination character(s), so there will be no '\n' character read.

For the empty line in the r.txt file you will get an empty or blank string, so instead of line 18, you can just write

while (((recordData = br.readLine()) != null) && !recordData.trim().isEmpty()))

The trim() method will cover cases where the blank line is not just a new line, but contains "white space" characters (e.g., SPACE and TAB).

On another note, the recordData declaration is not needed at all. You can just reuse the line variable.

Upvotes: 0

user695992
user695992

Reputation:

'\n' is a character and recordData is a String. You are more interested in the following answer

recordData = br.readLine();
while(recordData != null && !recordData.trim().isEmpty()) {
  System.out.print(recordData);
  recordData = br.readLine();
}

Upvotes: 3

Jigar Joshi
Jigar Joshi

Reputation: 240966

it never returns termination character

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Upvotes: 3

Related Questions