[英]Why does Java Scanner throw a NoSuchElementException unless I declare my Scanner by Path instead of File?
最初,我將我的掃描儀聲明為
Scanner in = new Scanner(new File(filename));
我讓它讀取了大約 3000 行的 CSV 文件,當它到達第 362 行時,它給了我一個“沒有這樣的元素”錯誤。 在我將聲明更改為后,錯誤消失了
Scanner in = new Scanner(Paths.get(filename));
但為什么這會有所作為?
這是我的 CSV 文件的第 360-362 行(在第 362 行讀取31
后出現“無此類元素”錯誤):
4,"T Sanchez, A Polyakov, JP Richard, D Efimov",1,29,0,0,0
3,"T Sánchez, JA Moreno, JA Peralta",4,30,0,0,0
3,"FAO Ricardez, T Sánchez, JA Moreno",5,31,0,0,0
這是我的代碼:
String filename = "before.csv";
Scanner in = new Scanner(new File(filename)); // changed to Paths.get(filename)
PrintStream out = new PrintStream(new File("after.csv"));
out.println(in.nextLine());
String DELIMITER = ",";
in.useDelimiter(DELIMITER);
while(in.hasNext()) {
int author_count = in.nextInt();
out.print(author_count + ",");
for(int i = 0; i < author_count; i++) {
String cur_author = in.next();
...
}
out.print("<bitmask>" + ",");
for(int i = 0; i < 4; i++) {
int a = in.nextInt(); // where the error occurred
out.print(a + ",");
}
out.println(in.nextLine().replace(",", ""));
}
in.close();
out.close();
謝謝!
區別在於代碼。
public Scanner(File source) throws FileNotFoundException {
this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
}
public Scanner(Path source) throws IOException
{
this(Files.newInputStream(source));
}
我相信第一種情況,因為它將它加載到緩沖區中,這就是它可能拋出 NoSuchElementException 的原因
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.