Appending Column at the End of a CSV File in Java

Question

https://stackoverflow.com/questions/68103693/appending-column-at-the-end-of-a-csv-file-java


I have a csv file and there is 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 gets written 2 times and also on the first column (Except the first one). How can I prevent it from doing it? I've been stuck in this problem from the 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();

}

}

Answer

Your task is to append a column to the original CSV file. The code will be lengthy if you try to do it in Java.

It is simple to accomplish the task using SPL, the open-source Java package. Only one line of code is enough:

A

1

=file("temp.csv").export@wc(file("test1.csv").import@wc().(~|="Marks,1,2".split@c()(#)))

 

SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as append.splx and invoke it in Java as you call a stored procedure:

Class.forName("com.esproc.jdbc.InternalDriver");

con= DriverManager.getConnection("jdbc:esproc:local://");

st=con.prepareCall("call append()");

st.execute();

Or execute the SPL string within a Java program as we execute a SQL statement:

st = con.prepareStatement("==file(\"temp.csv\").export@wc(file(\"test1.csv\").import@wc().(~|=\"Marks,1,2\".split@c()(#)))");
st.execute();

View SPL source code.