How do I tell if an empty line has been read in wi

2019-03-20 19:53发布

问题:

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.

回答1:

  1. Make sure you use: myString.equals("") not myString == "". After 1.6, you can use myString.isEmpty()
  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);
    }
  }
}


回答2:

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.



回答3:

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.



回答4:

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.



回答5:

try (BufferedReader originReader = getReader("now")) {
    if (StringUtils.isEmpty(originReader.readLine())) {
        System.out.printline("Buffer is empty");
    }