Appending column at the end of a csv file java

 

问题

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


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

}

}

解答

这个问题需要在原有的csv 上再追加一列。Java 实现则代码较长。

Java 下的开源包 SPL 很容易写,只要 1 句:


A

1

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

SPL提供了JDBC 供 JAVA 调用,把上面的脚本存为 append.splx,在 JAVA 中以存储过程的方式调用脚本文件:

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

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

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

st.execute();

或在JAVA 中以 SQL 方式直接执行 SPL 串:

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

SPL 源代码:https://github.com/SPLWare/esProc

问答搜集