[英]Using scanner for a multi-line text file
I'm working on a program that reads a text file. 我正在研究一个读取文本文件的程序。 I have to execute a separate method for each line of the file.
我必须为文件的每一行执行一个单独的方法。 I could do something like this:
我可以这样做:
LineNumberReader myReader = new LineNumberReader(new FileReader("filename"));
Scanner scanner = new Scanner(myReader.readLine());
while (scanner.hasNext()) { ... }
And put the latter two lines in a loop so I can parse the tokens for each line. 并将后两行放在一个循环中,这样我就可以解析每一行的标记。 But I was wondering if there is any way I can do this without instantiating a new scanner object every iteration.
但我想知道是否有任何方法可以做到这一点,而无需每次迭代都实例化一个新的扫描仪对象。
Java code to read each line with one scanner: 使用一个扫描程序读取每一行的Java代码:
Scanner myScanner = new Scanner(new File("filename"));
while (myScanner.hasNextLine())
{
String line = myScanner.nextLine();
...
}
You can combine the Reader and a Scanner, just pass the Reader into the Scanner, and then loop 您可以将Reader和扫描仪组合在一起,只需将Reader传递给扫描仪,然后循环
LineNumberReader myReader = new LineNumberReader(new FileReader("filename"));
Scanner myScanner = new Scanner(myReader); // <== scanner uses Reader
while (myScanner.hasNextLine()) {
String line = myScanner.nextLine();
}
@Max Zoome's example is a good approach but it has one problem that this loop will go to infinite
So i suggest you to use below version: @Max Zoome的例子是一个很好的方法,但它有一个问题,这个循环将
infinite
所以我建议你使用以下版本:
String line;
while (myScanner.hasNextLine() && (line=myScanner.nextLine()!=null))
{
// Do whatever you want to do
}
Alternative Solution 替代方案
When you want to read a file line by line
using BufferedReader is a good approach , 当你想使用BufferedReader
line by line
读取文件时line by line
是一个很好的方法,
Since Scanner
is used for parsing tokens from the contents of the stream as well as BufferedReader
is synchronized
and Scanner
is not . 由于
Scanner
用于从流的内容中解析令牌,因此BufferedReader
是synchronized
而Scanner
则不是。
FileReader in = new FileReader("yourFileName");
BufferedReader br = new BufferedReader(in);
while ((line=br.readLine()) != null) {
System.out.println(line);
}
in.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.