【发布时间】:2015-12-03 21:08:22
【问题描述】:
我正在用 Java 编写一个登录屏幕 GUI,它允许用户登录系统。该程序引用一个包含登录详细信息的 csv 文件,从中收集数据。
这和我看到的另一个问题类似,how to read csv into multidimensional array in Python
但就我而言,它是用 Java 编写的,而不是 Python
我正在尝试将在 Excel 中创建的 csv 文件中的数据读取到多维数组中。我了解如何将其读入数据变量,这是针对文本文件的每一行完成的。但是对于 try catch 块中的代码,它意味着将每行的每个字段分配给 usersData[ ][ ] 数组的一个元素,只会给我错误。
我已尽我所能修复它,但没有成功。
public static boolean determineifValid(String userID, String password){
boolean detailsValid = false;
// The name of the file
String file_Name = "PathologyInterfaceUsers.csv";
File file = new File(file_Name);
// The following code block reads the text file in the file_name variable.
String usersData[][] = new String[12][3];
// CSV - comma seperated values
String data;
int firstChar;
int field_No;
int i;
int j;
i = 0;
try{
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()){
data = inputStream.next();
// If the data record contains nothing that indicates the end of the file
if(data.equalsIgnoreCase("")){
// Nothing happens and nothing needs to be done
System.out.println("End of file reached ");
}else{
if(i == 0){
System.out.println("Record No: "+data);
}else{
System.out.println(i+" : "+data);
}
field_No = 0;
firstChar = 0;
for(j = 0; j < data.length(); j++){
/* If the current character is a comma separator, then the end of
* the data field has been reached.
*/
if((data.charAt(j)) == ','){
System.out.println("Field "+(field_No + 1)+" is being copied to"
+ " the data array");
usersData[i][field_No] = data.substring(firstChar, (j-1));
System.out.println("The data for field "+(field_No + 1)+"has been "
+ "assigned to the "+ (field_No + 1) +" column");
// The index of the 2nd element of usersData, 'field' is incremented by 1
field_No = field_No + 1;
System.out.println("The field_No has been incremented by 1");
/* The first character of the next field is the one after the
* comma (value divider)
*/
firstChar = j + 1;
System.out.println("Value divider ','");
}else if(j == data.length()){
usersData[i][field_No] = data.substring(firstChar, j);
}
}
i = i + 1;
}
}
inputStream.close();
}catch (FileNotFoundException e){
System.out.println("We are so sorry, but an error has occured! ");
}
【问题讨论】:
-
它给出了什么错误以及堆栈跟踪是什么?
-
如果没有错误,我们帮不了你太多,顺便说一下,我会尝试阅读每一行,然后用the split method of the String class分割它,为你节省很多时间
-
大家好。抱歉,我没有发布错误。但我不再需要了,因为我找到了一种更有效的读取 csv 的方法。在 Stack Overflow 的其他地方归档。我会把它发布给任何可能需要它的人。
标签: java csv multidimensional-array