Java append new column to csv file

后端 未结 3 990
旧时难觅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:03

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

提交回复
热议问题