Java append new column to csv file

后端 未结 3 993
旧时难觅i
旧时难觅i 2020-12-16 08:24

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

3条回答
  •  鱼传尺愫
    2020-12-16 09:04

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

提交回复
热议问题