Java 将新列附加到 csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34590971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:05:29  来源:igfitidea点击:

Java append new column to csv file

javacsvexport-to-csvfilewriter

提问by michael

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

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

Here is what I did:

这是我所做的:

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.

结果 - 它将新列附加到第一列下方,因此我只有一个长列。

Thanks,

谢谢,

采纳答案by dsp_user

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

您必须读取文件(逐行),然后将新列插入到每一行。这是使用 BufferedReader 和 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();
    }

}

回答by Fin

Something like this perhaps:

可能是这样的:

public void appendCol(String fileName, ???ArrayList??? data) { //assuming data is of type ArrayList here, you need to be more explicit when posting code

    String lineSep = System.getProperty("line.separator");
    String output = "";
    try{
        BufferedReader br = new BufferedReader(new  FileReader(fileName));
        String line = null;
        int i = 0;
        while ((line = br.readLine()) != null) {
            output += line.replace(
                    lineSep,
                    "," + String.valueOf(data.get(i)) + lineSep);
            i++;
        }
        br.close();
        FileWriter fw = new FileWriter(fileName, false); //false to replace file contents, your code has true for append to file contents
        fw.write(output);
        fw.flush();
        fw.close();
    } catch (Exception e){
        e.printStackTrace();
    } 
}

回答by Doss

Hope this will help you.

希望这会帮助你。

{
    //CREATE CSV FILE 
    StringBuffer csvReport = new StringBuffer(); 
    csvReport.append("header1,Header2,Header3\n"); 
    csvReport.append(value1 + "," + value2 + "," + value3 + "\n"); 

    generateCSVFile( filepath,fileName, csvReport); // Call the implemented mathod 
}

public void generateCSVFile(String filepath,String fileName,StringBuffer result)
{
    try{

    FileOutputStream fop = new FileOutputStream(filepath);

    // get the content in bytes
    byte[] contentInBytes = result.toString().getBytes();

    fop.write(contentInBytes);
    fop.flush();

    //wb.write(fileOut);
    if(fop != null)
        fop.close();
    }catch (Exception ex)
    {
        ex.printStackTrace();
    }
}