当我运行这个程序时出现异常,它的大文件充满了数据,我试图从该文件导入数据并将信息插入到二维数组中,但是该文件由大约 19,000 行组成。 不过,我的程序停止运行并告诉我在此过程中没有任何行。我的异常(exception)是 java.util.NoSuchElementException: 未找到行 在 java.util.Scanner.nextLine(Scanner.java:1585) 在 Data.main(Data.java:30)
请帮忙,这是怎么回事?
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Data
{
public static void main(String[] args)
{
try{
java.io.File file = new java.io.File("/Users/admin/Desktop/data.csv");
Scanner in = new Scanner(file);
String title = in.nextLine();
String[][] data = new String[19517][5];
int currentRow = 0;
String current;
int i = 0;
while (in.hasNextLine())
{
String[] c = new String[5];
String line = in.nextLine().replaceAll("\"", ""); //changing the format of the data input
c = line.split(",");
c[1] = c[1].replace(" ", "");
for (int j = 0; j <data[0].length; j++)
{
current = c[j];
data[i][j] = c[j];
}
i++;
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
最佳答案
Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.
这意味着您正在尝试读取不存在的数据。发生这种情况是因为 while
循环中的条件始终满足,导致 nextLine
尝试读取不存在的行。您应该将 while
循环更改为:
while(in.hasNextLine())
这确保nextLine
仅在有需要读取的行时才应用。
我制作了一个虚拟 csv
文件,它确实读取了所有行。
使用调试器会对您有很大帮助,我强烈推荐您使用它。
关于java - 将大数据导入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21520828/