简体   繁体   English

如何替换CSV文件中的特定行?

[英]How to replace a specific row from a CSV file?

Is it possible to access a specific row in a CSV file and replace a specific field in it? 是否可以访问CSV文件中的特定行并替换其中的特定字段? Eg like in this pseudo code: 例如像下面的伪代码:

Row row = csvFile.getRow(123);
row.getField(2).set("someString");

Tried Apache Commons CSV and OpenCSV , but can't figure out how to do it with them. 尝试过Apache Commons CSVOpenCSV ,但无法弄清楚如何使用它们。 Only way I can think of is to iterate through a file, store everything in a new object and create a file, but that doesn't seem like a good way. 我能想到的唯一方法是遍历文件,将所有内容存储在新对象中并创建文件,但这似乎不是一个好方法。

Thanks for any suggestion! 感谢您的任何建议!

Sounds like a duplicate of this one to me. 在我看来,这听起来像是重复的

I am not sure about how to do it with apache but I am sure they have the same mechanisms. 我不确定如何使用apache进行操作,但是我确定它们具有相同的机制。 In openCSV you would create an CSVReader to your source file and a CSVWriter to your destination file. 在openCSV中,您将为源文件创建CSVReader,并为目标文件创建CSVWriter。 Then read a record at a time, make any desired changes and write it out. 然后一次读取一条记录,进行任何所需的更改并将其写出。

Or, if the file is small, you can do a readAll and writeAll. 或者,如果文件很小,则可以执行readAll和writeAll。

But if you want to do it all in the same file read my comments in the duplicate . 但是,如果您想在同一个文件中全部进行操作,请阅读我的重复注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM