0

I have a text file. It is a simple database, that stores json objects line by line. One json object per one line. Lines are separated with "\n" character.

So my task is to get necessary object from file, deserialize it to java object, change some fields, and write object back to file. Replacing old line with new json line.

Is it possible to make this operation without opening the whole big file to memory, and then saving it? Just replacing bytes in 1 small line.

I read file line by line, and get nessesary line number. I deserialize object and change fields. But I can't find the correct way how to save it according to my goal. I tried FileWriter, BufferedWriter, but it didn't helped.

{"name":"John","surname":"Galt","email":"john@gmail.com"}
{"name":"John2","surname":"Galt","email":"john2@gmail.com"}
{"name":"John3","surname":"Galt","email":"john3@gmail.com"}
{"name":"John4","surname":"Galt","email":"john4@gmail.com"}
Aleksey Kurkov
  • 323
  • 2
  • 13
  • 1
    Unless the replacement consists of the same number of bytes, you cannot do that in any language in any way, I believe. At best you can overwrite everything from the line you change till the end of the file. – Fureeish Aug 29 '19 at 19:31
  • If the new line has a different length (which is a safe assumption that it will), then all bytes in the rest of the file **must be moved**. It is generally simpler to do it in one of two ways: 1) Read file into memory, update content, write file back to disk. --- 2) Copy file line-by-line, replacing lines as needed, there delete old file and rename new file. --- Option 1 is simpler. Option 2 can handle huge files without running out of memory. – Andreas Aug 29 '19 at 19:34

0 Answers0