我认为我的代码在 ArrayList 中存储数据是正确的。但是,我无法将列表转换为 String[][]。这是我的代码:
int row = 0;
int col = 0;
String fileInput = JOptionPane.showInputDialog(null,
"Please enter the path of the CSV file to read:");
File file = new File(fileInput);
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;
// Construct a new empty ArrayList for type String
ArrayList<String[]> al = new ArrayList<String[]>();
//read each line of text file
while((line = bufRdr.readLine()) != null) {
String[] columnData = line.split(",");
al.add(columnData);
}
// Convert ArrayList to String array
String[][] numbers = (String[][]) al.toArray(new String[al.size()][16]);
我收到一条错误消息,指出无法转换为 String[][] 类型。关于我能做什么有什么想法吗?
编辑:所以转换问题解决了(编辑后的代码粘贴在上面) - 现在它什么也不输出。我觉得我一定是错误地存储了数据。我应该添加/更改什么?
最佳答案
该数组将是 String[]
的 Object[]
,因此强制转换不起作用。您可以(并且应该)使用提供要填充的数组的 toArray()
版本:
String[][] numbers = (String[][]) al.toArray(new String[al.size()][]);
关于java - 存储 ArrayList 数据并转换为 String[][],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6983925/