[英]Scanning a text file with Java
The purpose is to print-out a list of names from a .txt file. 目的是从.txt文件中打印出名称列表。 The code I've used is below.
我使用的代码如下。
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileScanner3 {
public static void main(String args []) throws FileNotFoundException {
ArrayList<String> names = new ArrayList<String>();
String inName;
//Setup a scanner to read from a text file
Scanner in = new Scanner(new File("namefile.txt").getAbsoluteFile());
while (in.hasNextLine()) {
inName = in.next();
//Use next() to read string
names.add(inName);
}
//Tidy up by closing files
in.close();
//Print names ArrayList
for(int i =0; i<names.size(); i++) {
System.out.println((i + 1) + "\t" + names.get(i));
}
}
}
The error that I get is this: 我得到的错误是这样的:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at FileScanner3.main(FileScanner3.java:17)
If anyone is able to tell me what is wrong, that would be fantastic! 如果有人能够告诉我出什么问题了,那就太好了!
Edit: Spelling 编辑:拼写
Without the text file, it is hard to guess, but I suppose there is a blank line at the end of the file. 没有文本文件,很难猜测,但是我想在文件末尾有一个空白行。 You could prevent this error by chaning the inner loop to
您可以通过将内部循环更改为
while (in.hasNext()) {
inName = in.next();
//Use next() to read string
names.add(inName);
}
I hope it helps. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.