I'm reading in a text file formated like
word
definiton
word
definition
definition
word
definition
So I need to keep try of whether I'm in a definition or not based on when I reach those emtpy lines. Thing is, BufferedReader
discards \n
characters, and somehow comparing that empty line to String ""
is not registering like I thought it would. How can I go about doing this.
"".equals(myString)
(which is null
-safe) not myString == ""
.
myString.isEmpty()
(not null
-safe)myString.trim()
to get rid of extra whitespace before the above checkHere's some code:
public void readFile(BufferedReader br) {
boolean inDefinition = false;
while(br.ready()) {
String next = br.readLine().trim();
if(next.isEmpty()) {
inDefinition = false;
continue;
}
if(!inDefinition) {
handleWord(next);
inDefinition = true;
} else {
handleDefinition(next);
}
}
}
The BufferedReader.readLine()
returns an empty string if the line is empty.
The javadoc says:
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.
If you don't appear to be seeing an empty String, either the line is not empty, or you are not testing for an empty String correctly.
line = reader.readLine();
if ("".equals(line)) {
//this is and empty line...
}
I do not know how did you try to check that string is empty, so I cannot explain why it did not work for you. Did you probably use ==
for comparison? In this case it did not work because ==
compares references, not the object content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With