0

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

1 Answer 1

0

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

}
Sign up to request clarification or add additional context in comments.

3 Comments

I can see that values are getting added from second line to last column. but its ignoring all the headers and not writing to csv file. and also the in column 3 same value is adding in all the lines. im trying to pass that dynamically. Could you please suggest. eg : header|header2|header3| value1|value2|value3 (value 3 is getting repeatedly for all lines)
and also the in column 3 same value is adding in all the lines that is exactly what you code shows us
* but its ignoring all the headers and not writing to csv file.* shouldn't. It should be written in the line bw.write(line+System.lineSeparator());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.