我之前问了一个关于在java中将CSV文件转换为2D数组的问题。我完全重写了我的代码,它几乎是返工。我现在唯一的问题是它是向后打印。换句话说,列在行应该在的地方打印,反之亦然。下面是我的代码:
int [][] board = new int [25][25];
String line = null;
BufferedReader stream = null;
ArrayList <String> csvData = new ArrayList <String>();
stream = new BufferedReader(new FileReader(fileName));
while ((line = stream.readLine()) != null) {
String[] splitted = line.split(",");
ArrayList<String> dataLine = new ArrayList<String>(splitted.length);
for (String data : splitted)
dataLine.add(data);
csvData.addAll(dataLine);
}
int [] number = new int [csvData.size()];
for(int z = 0; z < csvData.size(); z++)
{
number[z] = Integer.parseInt(csvData.get(z));
}
for(int q = 0; q < number.length; q++)
{
System.out.println(number[q]);
}
for(int i = 0; i< number.length; i++)
{
System.out.println(number[i]);
}
for(int i=0; i<25;i++)
{
for(int j=0;j<25;j++)
{
board[i][j] = number[(j*25) + i];
}
}
基本上,2D数组应该有25行25列。在读取CSV文件时,我将其保存为String ArrayList,然后将其转换为一维int数组。任何意见将不胜感激。由于
如果你想在java中读取CSV文件,那么你可能需要使用OPEN CSV
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
public class CsvFileReader {
public static void main(String[] args) {
try {
System.out.println("n**** readLineByLineExample ****");
String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] col = null;
while ((col = csvReader.readNext()) != null)
{
System.out.println(col[0] );
//System.out.println(col[0]);
}
csvReader.close();
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae+" : error here");
}catch (FileNotFoundException e)
{
System.out.println("asd");
e.printStackTrace();
} catch (IOException e) {
System.out.println("");
e.printStackTrace();
}
}
}
,你可以从这里获得相关的jar文件