Java 使用扫描仪读取行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20311266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read line with Scanner
提问by Sharcoux
EDITfor further readers: the problem was that my input file was corrupted.
为更多读者编辑:问题是我的输入文件已损坏。
I don't understand what I'm doing wrong :
我不明白我做错了什么:
I was using this code :
我正在使用此代码:
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);
}
}
Which is working fine. Now, for some reason, I wanted to change for a Scanner. My code became :
哪个工作正常。现在,出于某种原因,我想换一个扫描仪。我的代码变成了:
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();
}
This time, we never enter the while, because r.hasNextLine() always returns "false". Any idea about what I'm doing wrong ?
这一次,我们从不输入 while,因为 r.hasNextLine() 总是返回“false”。知道我做错了什么吗?
I precise that nothing else changed, the file is still the same.
我确切地说没有其他改变,文件仍然相同。
EDIT: I also precise that I tried with another file and got the same result, meaning it doesn't comes from the file apparently.
编辑:我也确切地说我尝试了另一个文件并得到了相同的结果,这意味着它显然不是来自该文件。
The file looks like this :
该文件如下所示:
a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait
...
Edit 2 :The content of the file seems to be problematic since the problem persists only if I copy/paste the content from my file to another. In clear, if I write the content myself, it works, if I use a part of the content of my dico.txt file, it doesn't work. Any explanation ?
编辑 2 :文件的内容似乎有问题,因为只有当我将内容从我的文件复制/粘贴到另一个文件时,问题仍然存在。很明显,如果我自己编写内容,它会起作用,如果我使用我的 dico.txt 文件的一部分内容,它就不起作用。有什么解释吗?
Edit 3 :These are the links to my files. I advice you to avoid the dico.txt which is very huge.
编辑 3:这些是我的文件的链接。我建议您避免使用非常庞大的 dico.txt。
dico.txt : https://drive.google.com/file/d/0B0sroFy9HZlBNDl3MUwzVnh6VU0/edit?usp=sharing
dico.txt:https://drive.google.com/file/d/0B0sroFy9HZlBNDl3MUwzVnh6VU0/edit ?usp =sharing
test.txt : https://drive.google.com/file/d/0B0sroFy9HZlBemZjbXU1RmlmdjQ/edit?usp=sharing
test.txt : https://drive.google.com/file/d/0B0sroFy9HZlBemZjbXU1RmlmdjQ/edit?usp=sharing
采纳答案by Keerthivasan
This code reads the file line by line.
此代码逐行读取文件。
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();
}
}
You can also set a delimiter as a line separator and then perform the same.
您还可以将分隔符设置为行分隔符,然后执行相同的操作。
scanner.useDelimiter(System.getProperty("line.separator"));
You have to check whether there is a next token available and then read the next token. You will also need to doublecheck the input given to the Scanner. i.e. dico.txt. By default, Scanner breaks its input based on whitespace. Please ensure that the input has the delimiters in right place
您必须检查是否有下一个令牌可用,然后读取下一个令牌。您还需要仔细检查提供给扫描仪的输入。即 dico.txt。默认情况下,Scanner 根据空格中断其输入。请确保输入的分隔符在正确的位置
UPDATED ANSWER for your comment:
针对您的评论的更新答案:
I just tried to create an input file with the content as below
我只是尝试创建一个内容如下的输入文件
a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait
tried to read it with the below code.it just worked fine.
尝试使用以下代码阅读它。它运行良好。
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);
}
Output:
输出:
line : a
line : à
line : abaissa
line : abaissable
line : abaissables
line : abaissai
line : abaissaient
line : abaissais
line : abaissait
so, I am sure that this should work. Since you work in Windows ennvironment, The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. if you set your Scanner instance to use delimiter as follows, it will pick up probably
所以,我相信这应该有效。由于您在 Windows 环境中工作,因此行尾 (EOL) 序列 (0x0D 0x0A, \r\n) 实际上是两个 ASCII 字符,即 CR 和 LF 字符的组合。如果您将 Scanner 实例设置为使用分隔符如下,它可能会拾取
scr = new Scanner(file);
scr.useDelimiter("\r\n");
and then do your looping to read lines. Hope this helps!
然后循环读取行。希望这可以帮助!
回答by yuvalhuck
Try to use r.hasNext()instead of r.hasNextLine():
尝试使用r.hasNext()而不是r.hasNextLine():
while(r.hasNext()) {
scan = r.next();
回答by Nishant Lakhara
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() 和 nextLine() 方法与 Scanner 相关联,用于获取字符串输入。他们的区别是...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
next() 只能读取输入直到空格。它无法读取由空格分隔的两个单词。此外,next() 在读取输入后将光标置于同一行。
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
nextLine() 读取输入,包括单词之间的空格(即,它读取到行尾 \n)。读取输入后,nextLine() 将光标定位在下一行。
Read article :Difference between next() and nextLine()
Replace your while loop with :
将您的 while 循环替换为:
while(r.hasNext()) {
scan = r.next();
System.out.println(scan);
if(scan.length()==0) {continue;}
//treatment
}
Using hasNext()
and next()
methods will resolve the issue.
使用hasNext()
和next()
方法将解决问题。
回答by Zuhair Sagga
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1;
import java.io.File;
import java.util.Scanner;
/**
*
* @author zsagga
*/
class openFile {
private Scanner x ;
int count = 0 ;
String path = "C:\Users\zsagga\Documents\NetBeansProjects\JavaApplication1\src\javaapplication1\Readthis.txt";
public void openFile() {
// System.out.println("I'm Here");
try {
x = new Scanner(new File(path));
}
catch (Exception e) {
System.out.println("Could not find a file");
}
}
public void readFile() {
while (x.hasNextLine()){
count ++ ;
x.nextLine();
}
System.out.println(count);
}
public void closeFile() {
x.close();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1;
/**
*
* @author zsagga
*/
public class JavaApplication1 {
public static void main(String[] args) {
// TODO code application logic here
openFile r = new openFile();
r.openFile();
r.readFile();
r.closeFile();
}
}
回答by Squirrel in training
For everybody who still can't read in a simple .txt file with the Java scanner.
对于仍然无法使用 Java 扫描仪读取简单 .txt 文件的每个人。
I had the problem that the scanner couldn't read in the next line, when I Copy and Pasted the information, or when there was to much text in my file.
当我复制和粘贴信息时,或者当我的文件中有太多文本时,我遇到了扫描仪无法读取下一行的问题。
The solution is: Coder your .txt file into UTF-8.
This can be done fairly simple by saving opening the file again and changing the coding to UTF-8. (Under Win7 near the bottom right corner)
解决方案是:将您的 .txt 文件编码为 UTF-8。
这可以通过保存再次打开文件并将编码更改为 UTF-8 来实现,这非常简单。(Win7下靠近右下角)
The Scanner shouldn't have any problem after this.
在此之后,扫描仪应该没有任何问题。