我正在阅读格式如下的文本文件
word
definiton
word
definition
definition
word
definition
所以我需要根据我何时到达那些空行来继续尝试我是否在定义中。事情是,BufferedReader
丢弃\n
字符,并且以某种方式将该空行String ""
与我想的那样进行比较并没有注册。我该怎么做。
我正在阅读格式如下的文本文件
word
definiton
word
definition
definition
word
definition
所以我需要根据我何时到达那些空行来继续尝试我是否在定义中。事情是,BufferedReader
丢弃\n
字符,并且以某种方式将该空行String ""
与我想的那样进行比较并没有注册。我该怎么做。
"".equals(myString)
(这是-安全的null
) not myString == ""
.
myString.isEmpty()
(not null
-safe)myString.trim()
在上述检查之前使用去除多余的空格这是一些代码:
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);
}
}
}
如果该BufferedReader.readLine()
行为空,则返回一个空字符串。
javadoc说:
返回: 包含行内容的字符串,不包括任何行终止字符,如果已到达流的末尾,则返回 null。
如果您似乎没有看到空字符串,则该行不为空,或者您没有正确测试空字符串。
line = reader.readLine();
if ("".equals(line)) {
//this is and empty line...
}
我不知道您是如何尝试检查该字符串是否为空的,所以我无法解释为什么它对您不起作用。您可能==
用于比较吗?在这种情况下,它不起作用,因为==
比较的是引用,而不是对象内容。
此代码片段跳过空行,仅打印带有内容的行。
String line = null;
while ((line = br.readLine()) != null) {
if (line.trim().equals("")) {
// empty line
} else {
System.out.println(line);
}
}
仅包含空白字符的行也会被跳过。
try (BufferedReader originReader = getReader("now")) {
if (StringUtils.isEmpty(originReader.readLine())) {
System.out.printline("Buffer is empty");
}