I have a csv file and I have some data in it and I want to append a column in it. e.g:
Name,Age,Marks
Joe,15,1
Smith,20,2
I want to append that Marks Column through code. The problem I'm getting is
Name,Age,Marks
Joe,15
1
2
Smith,20
1
2
The data is getting written 2 times and also the on the first column (Except the first one). How can I prevent it from doing it ? I've been stuck in this problem from past 1 week
My code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class appendCol {
public static String appendingCol() {
String stringArray[] = {"Marks", "1", "2"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < stringArray.length; i++) {
sb.append(stringArray[i]);
}
String str = sb.toString();
return str;
}
public static void main(String[] args) throws IOException {
String line = "";
BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\temp.csv"));
try (BufferedReader br = new BufferedReader(new FileReader("D:\\text1.csv"))) {
while ((line = br.readLine()) != null) {
String newFileLine = line + "," + appendingCol();
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
}
}