Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 250
Aerlusch Avatar asked Dec 04 '12 15:12

Aerlusch


3 Answers

  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);
    }
  }
}
like image 71
durron597 Avatar answered Sep 27 '22 18:09

durron597


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.

like image 45
Stephen C Avatar answered Sep 27 '22 17:09

Stephen C


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.

like image 26
AlexR Avatar answered Sep 27 '22 17:09

AlexR