Java将新列追加到csv文件

我想计算一些列数据并将其csv作为列写入文件。然后,在计算了另一列数据之后,我想将其附加到同一文件中,但作为新列。

这是我所做的:

try {

FileWriter writer = new FileWriter(OUT_FILE_PATH, true);

for (int i=0; i<data.size(); i++) {

writer.append(String.valueOf(data.get(i)));

writer.append(",");

writer.append("\n");

}

writer.flush();

writer.close();

} catch (Exception e) {}

结果-它将新列追加到第一列下方,因此我只有一个长列。

谢谢,

回答:

您将必须逐行读取文件,然后将新列插入每一行。这是使用BufferedReader和BufferedWriter的解决方案

public void addColumn(String path,String fileName) throws IOException{

BufferedReader br=null;

BufferedWriter bw=null;

final String lineSep=System.getProperty("line.separator");

try {

File file = new File(path, fileName);

File file2 = new File(path, fileName+".1");//so the

//names don't conflict or just use different folders

br = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;

bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2)));

String line = null;

int i=0;

for ( line = br.readLine(); line != null; line = br.readLine(),i++)

{

String addedColumn = String.valueOf(data.get(i));

bw.write(line+addedColumn+lineSep);

}

}catch(Exception e){

System.out.println(e);

}finally {

if(br!=null)

br.close();

if(bw!=null)

bw.close();

}

}

以上是 Java将新列追加到csv文件 的全部内容, 来源链接: utcz.com/qa/434444.html

回到顶部