我試圖使用OpenCSV從一個CSV文件中讀取數據。然後,我想從輸入的csv中複製所有數據,並將其輸出到另一個csv文件,同時添加一個包含信息的新列。OpenCSV - 在添加列時將一個csv文件複製到另一個csv文件
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循環,所有其他代碼保持不變):
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」列。
這會逐行讀取正確嗎?我如何編輯這個以便逐列讀取? – Felix
@Felix是的。爲了逐列讀取,您必須讀取整個文件,因爲'csv'逐行存儲數據。要讀取整個文件,請使用'reader.readAll()'。如果無法將整個文件存儲在RAM中,則可以創建一個例如'ArrayList',然後讀取一行,將需要的列添加到列表中,重複。 –
Poohl
但是,使用.readAll()不起作用,因爲.readALL()需要一個列表。 @Poohl – Felix