Skip to content
Advertisement

How do I tell if an empty line has been read in with a BufferedReader?

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.

Advertisement

Answer

  1. Make sure you use: "".equals(myString) (which is null-safe) not myString == "".
    • After 1.6, you can use myString.isEmpty() (not null-safe)
  2. 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);
    }
  }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement