OpenCSV-在添加列时将一个csv文件复制到另一个 [英] OpenCSV - copying one csv file to another while adding a column
问题描述
我正在尝试使用OpenCSV读取一个CSV文件.然后,我想从输入的csv复制所有数据并将其输出到另一个csv文件,同时添加带有信息的新列.
I am trying to read from one CSV file using OpenCSV. I then want to copy all the data from the input csv and output it to another csv file while adding a new column with information.
public void run_streets_tsv( String tsvIn, String tsvOut) throws Exception
{
CSVReader reader = null;
CSVWriter writer = null;
try
{
reader = new CSVReader((new FileReader(tsvIn)));
writer = new CSVWriter(new FileWriter(tsvOut), '\t');
String element [] = null;
List<String[]> a = new ArrayList<String[]>();
while((element = reader.readNext()) != null){
for(int i = 0; i<element.length; i++){
a.add(i, element);
//a.add("JSON"); need to add this json element at the end of each column
}
}
writer.writeAll(a);
}
catch(Exception e)
{
throw e;
}
finally
{
reader.close();
writer.close();
}
}
我正在尝试的另一种方法是这样的(更改while循环,所有其他代码保持不变):
Another method I am trying is like this (changing the while loop, all other code remains the same):
String element [] = null;
while((element = reader.readNext()) != null){
ArrayList list = new ArrayList(Arrays.asList(reader));
list.add(element);
list.add("JSON");
writer.writeNext(element);
}
这确实可以正确打印所有行,但只是复制而已.我想添加额外的"JSON"列及其数据.
This does correctly print all the lines, but it just copies. I want to add that extra "JSON" column with its data.
推荐答案
以下代码将 element
-Array放大1,从而使您可以在新创建的最后一个索引中放入内容.然后只需保存该数组即可.
The following "enlarges" the element
-Array by one, enabling you to put something in the newly created last index. Then just save that array.
import java.util.Arrays;
String element[] = null;
while((element = reader.readNext()) != null){
element = Arrays.copyOf(element, element.length + 1);
element[element.length - 1] = "JSON";
writer.writeNext(element);
}
这篇关于OpenCSV-在添加列时将一个csv文件复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!