Priya
Priya

Reputation: 1

How to add values to specific column in existing csv file using java

For example header1,header2,header3 are there in csv file and how to add values to header3 column in existing csv file. Below is my code and trying to add values to column3.

BufferedReader br=null;
BufferedWriter bw=null;

try {
    File file = new File("ResponseTest.csv");
    File newfile = new File("ResponseTestNew.csv");

    br = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;  //old file includes header 1,header2
    bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newfile))); //new file

    String line = null;
    String value3= "7898798";

    while((line = br.readLine())!=null){
        String addedValue = "\t"+"value3";  // adding value to column -header3
        bw.write(line+addedValue +System.lineSeparator());
    }
} catch(Exception e){
    System.out.println(e);
} finally  {
    br.close();
    bw.close();
}

output is :

header1|header2|header3 value3
value1|value2|value3

problem is value3 is getting added from first row of header3

enter image description here

Upvotes: 0

Views: 578

Answers (1)

Jens
Jens

Reputation: 69460

You should ignore line one in your loop:

boolean isFirstLine = true;
while((line = br.readLine())!=null){
    if (isFirstline){
       bw.write(line+System.lineSeparator());
       isFirstline = false;
       continue;
    }
    bw.write(line+ "\t"+"value3"+System.lineSeparator());

}

Upvotes: 0

Related Questions