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.
- Make sure you use:
myString.equals("")
not myString == ""
. After 1.6, you can use myString.isEmpty()
- You can use
myString.trim()
to get rid of extra whitespace before the above check
Here'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.
This code snippets skips the empty line and only prints the ones with content.
String line = null;
while ((line = br.readLine()) != null) {
if (line.trim().equals("")) {
// empty line
} else {
System.out.println(line);
}
}
Lines only containing whitespace characters are also skipped.
try (BufferedReader originReader = getReader("now")) {
if (StringUtils.isEmpty(originReader.readLine())) {
System.out.printline("Buffer is empty");
}