Java append new column to csv file

We Are Going To Discuss About Java append new column to csv file. So lets Start this Java Article.

Java append new column to csv file

  1. Java append new column to csv file

    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

  2. Java append new column to csv file

    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

Solution 1

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

Original Author Fin Of This Content

Solution 2

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

}

Original Author dsp_user Of This Content

Solution 3

I have used apache-commons for resolving this issue. There was no perfect answer that worked for me. After a lot of effort, this worked for me.

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

Original Author Dasari Swaroop Kumar Of This Content

Solution 4

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

Original Author Doss Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment