java - readLine() 方法返回空字符串,BufferedReader

标签 java readline

我正在执行 java 代码。 readLine() 方法从文本文件返回一个空字符串,即使文件中有文本也是如此。

BufferedReader csv =  new BufferedReader(new FileReader("D:/SentiWordNet_3.0.0/home/swn/www/admin/dump/senti.txt"));
String line = "";      
while((line = csv.readLine()) != null){ 
    String[] data = line.split("\t");
    Double score = Double.parseDouble(data[2])-Double.parseDouble(data[3]);
}

split()调用后,抛出异常Arrayindexoutofboundsexception
下面是文本文件。每行以 “a” 开头,后跟一个数字。该代码能够检索带有 apocrine 一词的行,但无法检索带有 eccrine 一词的行。当我在 Debug模式下运行时,行变量返回为空字符串。

a 00098529 0 0 apocrine#1 (of exocrine glands) producing a secretion in which part of the secreting cell is released with the secretion; "mother's milk is one apocrine secretion"

a 00098736 0.25 0 eccrine#1 (of exocrine glands) producing a clear aqueous secretion without releasing part of the secreting cell; important in regulating body temperature

a 00098933 0 0 artesian#1 (of water) rising to the surface under internal hydrostatic pressure; "an artesian well"; "artesian pressure"

我是否应该使用其他结构来读取文本文件中的行

最佳答案

你可以在readline()的javadoc中看到在 BufferedReader 下面..

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

因此,如果您的文本包含一个换行符 ('\n') 后跟一个回车符,BufferedReader 将返回一个空字符串。考虑以下字符串。

abc\n\rdef

如果您调用 readLine(),这将返回 "abc""""def" 3次。不仅是上面的String,下面的String也可能导致同样的结果。

abc\n\ndef

abc\r\rdef

在您的文本文件中,它必须包含这些组合中的一种或多种。或者它可能在这些特殊字符之间包含 whitespases。例如:

abc\n\t\ndef

abc\n \rdef

and so on...

这就是为什么你得到一个空行。

要解决这个问题,您可以在 while-loop 中检查该行是否为空。

while ((line = csv.readLine()) != null) {
    if(line.trim().isEmpty()){
        continue;
    }
    //Your code
}

关于java - readLine() 方法返回空字符串,BufferedReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18532602/

相关文章:

java - 是否可以让 Castor 编码(marshal)/取消编码(marshal) EnumMap?

c - 我怎样才能抑制 readline 打印一些东西然后恢复它?

ruby-on-rails - Windows 下的 Rails 3 readline 问题

Python.readline()

java - 如何使用 split() 来分割一行

java - 启用 html 的 android ListView

java - Android下的测试境界

java - Java中删除所有链表

java - 将 Selenium 与 HP ALM 集成