我正在按如下方式处理一个文件并关闭它。稍后,我会进行更多处理,并获得一些ID,我想将其附加到以前生成的CSV中的所有行。因此,所有行都将具有相同的值。
我创建并将数据附加到csv的初始代码:
private StringBuilder stringBuilder = new StringBuilder();
public void writeToFile(String[] tIds, PrintWriter printWriter) throws DataNotFoundException {
int rowCount = 0;
for(String id: tIds) {
Data data = util.getData(id);
csvHelper.prepareFileData(data, this.stringBuilder);
rowCount++;
if (rowCount == CHUNK_SIZE) {
printWriter.println(this.stringBuilder.toString());
this.stringBuilder = new StringBuilder();
rowCount = 0;
}
}
printWriter.close();
}
现在,进一步的处理将返回一些processedID
,我希望将其作为新列附加到所有行。
一种选择是:
public void appendAgain(String processedId) {
BufferedReader br = new BufferedReader(new FileReader(feedFile));
String output = "";
String line;
while ((line = br.readLine()) != null) {
output += line.replace(",", "," + alertId + ",");
}
FileWriter fw = new FileWriter(feedFile, false); //false to replace file contents, your code has true for append to file contents
fw.write(output);
fw.flush();
fw.close();
}
public void prepareFileForData(Data data, StringBuilder sb) {
// map values from data to sb
sb.append(data.getId());
sb.append(",");
sb.append(data.getName());
.. and so on
}
请评论更好的方式或对当前方式的任何建议。谢谢
将其作为sed
命令执行:
sed -i '' 's/$/,<myProcessedID>/' myfile.csv
它可以在终端中运行,也可以使用ProcessBuilder
从java运行。