我有下面的Java代码用于读取csv文件,但输出为NULL。代码读取文件并将其分配给一个双数组。
import java.io.*;
import java.util.*;
public class CSVReader {
public static void main(String[] args) throws IOException {
try {
double[][] Data = null;
Data = CSVReader.read("C:\Users\mrezz\Data.csv", true);
System.out.println(Arrays.deepToString(Data));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public static double[][] read(String theFile, boolean hasTitle) throws IOException {
try {
boolean firstTime = true;
double[][] data = null;
File file = new File(theFile);
int row = 0;
int col = 0;
BufferedReader reader = new BufferedReader(new FileReader(file));
bufferedReader.close();
String line;
if (hasTitle) {
line = reader.readLine();
}
while ((line = reader.readLine()) != null) {
if (firstTime) {
firstTime = false;
StringTokenizer st = new StringTokenizer(line, ",");
col = 0;
while (st.hasMoreTokens()) {
st.nextToken();
col++;
}
data = new double[row][col];
col = 0;
continue;
}
StringTokenizer st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
data[row][col] = Double.valueOf(st.nextToken());
col++;
}
col = 0;
row++;
}
return data;
} catch (Exception e) {
return null;
}
}
}
代码应将文件分配给(double[][]数据)数组。
有任何帮助请
您可能会得到一个异常并返回null
而不向用户报告。
我怀疑上面代码中的最后一个return null;
。