0

Is it possible to access a specific row in a CSV file and replace a specific field in it? E.g. 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. 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!

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
ss1
  • 1,009
  • 15
  • 32
  • Possible duplicate of [Java Replace Line In Text File](http://stackoverflow.com/questions/20039980/java-replace-line-in-text-file) – Andy Turner Nov 10 '15 at 14:39
  • 4
    "that doesn't seem like a good way" <-- but _that_ is the way. You never replace text in a file inline. – fge Nov 10 '15 at 14:39

1 Answers1

1

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. In openCSV you would create an CSVReader to your source file and a CSVWriter to your destination file. 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.

But if you want to do it all in the same file read my comments in the duplicate.

Community
  • 1
  • 1
Scott Conway
  • 975
  • 7
  • 13