【问题标题】:Java append new column to csv fileJava将新列附加到csv文件
【发布时间】:2016-04-08 01:19:20
【问题描述】:

我想计算一些列数据并将其作为列写入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) {} 

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

谢谢,

【问题讨论】:

  • 你用\n做什么?这可能会导致这些问题。
  • @tbrown 如果我删除 \n 我得到单行
  • 我不知道你的数据结构,但是如果你知道列数,你可以使用两个循环,即每行一个for-loop,在一个之后使用\n行已完成。
  • @tbrown 正如我所提到的,数据结构很简单:每次调用此方法时,我都需要将单列简单整数放入其中。每次调用此方法时,我一次只知道 1 列。

标签: java csv export-to-csv filewriter


【解决方案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();
    }

}

【讨论】:

  • 基本上你建议每次写入一个新文件——tmp文件,最后追加到包含所有其他好列的最终文件?
  • 或者直接删除旧文件,将新文件重命名为原名。
  • 是的,我知道了,它有效,需要将 line+addedColumn+lineSep 更改为 line+","+addedColumn+lineSep
  • 这个例子中的数据是什么?它应该是 CSV 文件吗?
【解决方案2】:

希望这会对您有所帮助。

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

【讨论】:

  • 错误答案。但是如果他想逐行而不是逐列写入文件,他会怎么做?
  • 您只需复制文件字节。那应该有什么用?不是问题的答案。
【解决方案3】:

可能是这样的:

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

【讨论】:

    【解决方案4】:

    我使用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);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-30
      • 2014-05-13
      • 2020-06-05
      • 2019-03-26
      • 2021-09-07
      • 2021-07-21
      • 2019-11-06
      相关资源
      最近更新 更多