我在执行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"开头,后面跟着一个数字。该代码能够检索这一行中的假冒伪劣词,但不能检索到带有单词eccrine的行。在调试模式下运行时,行变量返回为空字符串。
分泌一种分泌细胞的00098529 0 0 apocrine#1 (外分泌腺体),分泌细胞的一部分随分泌而释放;“母乳是一种高分泌” (外分泌腺体)在不释放部分分泌细胞的情况下产生清晰的水分泌的00098736 .2.250 eccrine#1;在调节体温方面很重要 在内部静水压力下上升到地面的00098933 .0 0 artesian#1;“自流井”;“自流压力”
我应该使用其他构造来读取文本文件中的行吗?
发布于 2013-08-30 12:24:00
下面是从文件中读取数据的示例方法。
在这里,读取完每一行后,将每一行添加到数组列表中,并返回数组列表。
public ArrayList<String> fileRead(String fileName){
File f;
String s;
FileReader fr = null;
BufferedReader br = null;
ArrayList<String> sl = new ArrayList<String>();
try {
f = new File(fileName);
fr = new FileReader(f);
br = new BufferedReader(fr);
while((s=br.readLine())!=null){
sl.add(s);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(br!=null)
br.close();
if(fr!=null)
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return sl;
}发布于 2015-12-25 03:01:48
您可以在读行()的javadoc中看到BufferedReader中的以下内容。
读一行文字。行被认为是由一个行提要('\n')、一个回车('\r')或一个运输返回(后面紧接着是linefeed )中的任何一个终止的。
因此,如果您的文本包含一个行提要('\n')和一个回车返回,BufferedReader将返回一个空字符串。考虑下面的字符串。
abc\n\rdef
这将返回"abc"、""、"def",如果您调用readLine() 3次。不仅上述字符串,下面的字符串还可能导致相同的结果。
abc\n\n abc\r\rdef
在文本文件中,它必须包含这些组合中的一个或多个。或者它可能在这些特殊字符之间包含whitespases。例如:
美国广播公司 abc\n \rdef 等等..。
所以你才会有空话。
要克服这个问题,可以检查while-loop中的行是否为空。
while ((line = csv.readLine()) != null) {
if(line.trim().isEmpty()){
continue;
}
//Your code
}发布于 2013-08-30 12:35:34
试着使用扫描仪:
Scanner in = new Scanner(new FileReader("filename.txt"));
while (in.hasNext()){
String str = in.next());
// Use it
}https://stackoverflow.com/questions/18532602
复制相似问题