簡體   English   中英

將值從多維數組寫入Java中的CSV文件

[英]Write values from multidimensional array to csv file in java

我編寫了一個小型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++;
}

您可以使用這樣的東西...

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM