将值从多维数组写入java中的csv文件

时间:2013-10-21 11:17:26

标签: java csv multidimensional-array

我编写了一个小型Java程序,它从CSV文件中读取数据,我必须将这些值保存在二维数组中。现在我需要将这些值(不是所有信息都将被存储,因为数组包含许多冗余数据)从此数组写入新的CSV文件。任何人都可以帮我一个代码示例,我搜索了很多,但找不到答案。我的代码是:

int row = 0;
int col = 0;
String[][] numbers=new String[24][24];

File file = new File("D:\\thesis\\sorted_file.csv");
if(file.exists())
{
    System.out.println("file exist");
}   

BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;
String delims=",";

//read each line of text file
while((line = bufRdr.readLine()) != null )
{
    StringTokenizer st = new StringTokenizer(line,delims);

    col=0;
    while (st.hasMoreTokens())
    {
        //get next token and store it in the array
        numbers[row][col] = st.nextToken();
        System.out.print("number["+row+"]["+col+"]:"+numbers[row][col]);
        col++;
    }
    row++;
}

1 个答案:

答案 0 :(得分:0)

你可以使用这样的东西......

BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
StringBuilder sb = new StringBuilder();
for (String element : numbers) {
sb.append(element);
sb.append(",");
}

br.write(sb.toString);
br.close();