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(); } }
Advertisement
Answer
With this as input in text1.csv:
Name,Age Joe,15 Smith,20
I ran (very tightly adapted from your code):
static void tryStackOverflow () { String line = ""; try { BufferedWriter writer = new BufferedWriter (new FileWriter ("temp.csv")); BufferedReader br = new BufferedReader (new FileReader ("text1.csv")); while ((line = br.readLine ()) != null) { String newFileLine = line + "," + appendingCol (); writer.write (newFileLine); writer.newLine (); } writer.close (); } catch (IOException excep) { System.err.println ("Exception " + excep); } } 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; }
and that produced:
Name,Age,Marks12 Joe,15,Marks12 Smith,20,Marks12
Then it seems clear that stringArray
should be be in the other method (your main method) and added to line by line. Your code also assumes there are as many lines as elements in that array. But disregarding that, I moved the array and eliminated the appendingCol
method and ran this:
static void tryStackOverflow () { String line = ""; String stringArray[] = { "Marks", "1", "2" }; int lineNum = 0; try { BufferedWriter writer = new BufferedWriter (new FileWriter ("temp.csv")); BufferedReader br = new BufferedReader (new FileReader ("text1.csv")); while ((line = br.readLine ()) != null) { String newFileLine = line + "," + stringArray [lineNum++]; writer.write (newFileLine); writer.newLine (); } writer.close (); } catch (IOException excep) { System.err.println ("Exception " + excep); } }
which produced this:
Name,Age,Marks Joe,15,1 Smith,20,2