Java将新列附加到csv文件

时间:2016-01-04 12:16:52

标签: java csv export-to-csv filewriter

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

这是我做的:

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) {} 

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

谢谢,

4 个答案:

答案 0 :(得分:1)

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

}

答案 1 :(得分:1)

或许这样的事情:

toggle

答案 2 :(得分:0)

我已使用 apache-commons 来解决此问题。没有完美的答案对我有用。经过很多努力,这对我有用。

Writer writer = Files.newBufferedWriter(Paths.get("output.csv"));
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
//add whichever column you want in withHeader
                .withHeader("createdTs", "destroyedTs", "channelName", "uid", "suid", "did", "joinTs", "leaveTs", "platform", "location", "consumption"));

//actual columns in your passed CSV
 String[] HEADERS = {"createdTs", "destroyedTs",    "channelName", "uid", "suid", "did", "joinTs", "leaveTs", "platform", "location"};
    Reader in = new FileReader(yourCsvFile);
    Iterable<CSVRecord> records = CSVFormat.DEFAULT
            .withHeader(HEADERS)
            .withFirstRecordAsHeader()
            .parse(in);

    for (CSVRecord row : records) {
        String tempValue = String.valueOf(Long.parseLong(row.get("leaveTs")) - Long.parseLong(row.get("joinTs")));
        csvPrinter.printRecord(row.get("createdTs"), row.get("destroyedTs"),row.get("channelName"), row.get("uid"),
                                 row.get("suid"), row.get("did"), row.get("joinTs"), row.get("leaveTs"),
                                 row.get("platform"), row.get("location"), tempValue);
    }

答案 3 :(得分:-1)

希望这会对你有所帮助。

{
    //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();
    }
}