Java将新列附加到csv文件 [英] Java append new column to csv file

查看:224
本文介绍了Java将新列附加到csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算一些列数据并将其作为列写入 csv 文件。然后在计算其他数据列之后,我想将它附加到同一个文件但作为新列。

I want to calculate some column data and write it to csv file as column. Then after calculating other column of data I want to append it to same file but as new column.

这是我做的:

try {
    FileWriter writer = new FileWriter(OUT_FILE_PATH, true);
    for (int i=0; i<data.size(); i++) {
        writer.append(String.valueOf(data.get(i)));
        writer.append(",");
        writer.append("\n");
    }
    writer.flush();
    writer.close();
} catch (Exception e) {} 

结果 - 它将新列附加到第一列,所以我有一个长列。

Result - It appends the new column below the first column, so I have single long column.

谢谢,

推荐答案

您必须逐行读取文件,然后将新列插入每一行。这是使用BufferedReader和BufferedWriter的解决方案

You will have to read your file (line by line) and then insert the new column to every line. Here's a solution using BufferedReader and BufferedWriter

public void addColumn(String path,String fileName) throws IOException{
    BufferedReader br=null;
    BufferedWriter bw=null;
    final String lineSep=System.getProperty("line.separator");

    try {
        File file = new File(path, fileName);
        File file2 = new File(path, fileName+".1");//so the
                    //names don't conflict or just use different folders

        br = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2)));
        String line = null;
                    int i=0;
        for ( line = br.readLine(); line != null; line = br.readLine(),i++)
        {               

            String addedColumn = String.valueOf(data.get(i));
            bw.write(line+addedColumn+lineSep);
    }

    }catch(Exception e){
        System.out.println(e);
    }finally  {
        if(br!=null)
            br.close();
        if(bw!=null)
            bw.close();
    }

}

这篇关于Java将新列附加到csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆