编辑供更多读者引用:问题是我的输入文件已损坏。
我不明白我做错了什么:
我正在使用此代码:
File f = new File("C:\\Temp\\dico.txt");
BufferedReader r = null;
try {
r = new BufferedReader(new FileReader(f));
String scan;
while((scan=r.readLine())!=null) {
if(scan.length()==0) {continue;}
//treatment
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(r!=null) try {
r.close();
} catch (IOException ex) {
Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
}
}
哪个工作正常。现在,出于某种原因,我想换一个扫描仪。我的代码变成了:
File f = new File("C:\\Temp\\dico.txt");
Scanner r = null;
try {
r = new Scanner(f);
String scan;
while(r.hasNextLine()) {
scan = r.nextLine();
if(scan.length()==0) {continue;}
//treatment
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(r!=null) r.close();
}
这一次,我们从不输入 while,因为 r.hasNextLine() 总是返回“false”。知道我做错了什么吗?
我确定没有其他变化,文件还是一样的。
EDIT :我还准确地说我尝试使用另一个文件并得到相同的结果,这意味着它显然不是来自该文件。
文件如下所示:
a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait
...
编辑 2: 该文件的内容似乎有问题,因为只有当我将内容从我的文件复制/粘贴到另一个文件时问题仍然存在。很明显,如果我自己编写内容,它会起作用,如果我使用我的 dico.txt 文件的一部分内容,它就不起作用。有什么解释吗?
编辑 3: 这些是我的文件的链接。我建议您避免使用非常庞大的 dico.txt。
dico.txt : https://drive.google.com/file/d/0B0sroFy9HZlBNDl3MUwzVnh6VU0/edit?usp=sharing
test.txt : https://drive.google.com/file/d/0B0sroFy9HZlBemZjbXU1RmlmdjQ/edit?usp=sharing
最佳答案
此代码逐行读取文件。
public static void readFileByLine(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
您也可以将分隔符设置为行分隔符,然后执行相同操作。
scanner.useDelimiter(System.getProperty("line.separator"));
您必须检查是否有下一个 token 可用,然后读取下一个 token 。您还需要仔细检查提供给扫描仪的输入。即dico.txt。默认情况下,Scanner 会根据空格中断其输入。请确保输入的分隔符在正确的位置
您的评论的更新答案:
我只是尝试创建一个内容如下的输入文件
a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait
尝试使用下面的代码阅读它。它工作正常。
File file = new File("/home/keerthivasan/Desktop/input.txt");
Scanner scr = null;
try {
scr = new Scanner(file);
while(scr.hasNext()){
System.out.println("line : "+scr.next());
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ScannerTest.class.getName()).log(Level.SEVERE, null, ex);
}
输出:
line : a
line : à
line : abaissa
line : abaissable
line : abaissables
line : abaissai
line : abaissaient
line : abaissais
line : abaissait
所以,我相信这应该可行。由于您在 Windows 环境中工作,因此行尾 (EOL) 序列 (0x0D 0x0A,\r\n) 实际上是两个 ASCII 字符,即 CR 和 LF 字符的组合。如果您将 Scanner 实例设置为使用如下分隔符,它可能会拾取
scr = new Scanner(file);
scr.useDelimiter("\r\n");
然后循环读取行。希望这会有所帮助!
关于java - 用 Scanner 读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20311266/