简体   繁体   English

如何判断是否已使用 BufferedReader 读入空行?

[英]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.事实是, BufferedReader丢弃了\\n字符,并且以某种方式将该空行与String ""进行比较并没有像我想象的那样注册。 How can I go about doing this.我该怎么做呢。

  1. Make sure you use: "".equals(myString) (which is null -safe) not myString == "" .确保您使用: "".equals(myString) (它是null )而不是myString == ""
    • After 1.6, you can use myString.isEmpty() (not null -safe) 1.6 之后,您可以使用myString.isEmpty() (非null
  2. You can use myString.trim() to get rid of extra whitespace before the above check您可以在上述检查之前使用myString.trim()去除多余的空格

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.如果该行为空,则BufferedReader.readLine()返回一个空字符串。

The javadoc says: javadoc说:

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.返回: 包含行内容的字符串,不包括任何行终止字符,如果已到达流的末尾,则返回 null。

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");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM