Delete line from file in java

Ok, so I am trying to remove lines from a text file using java. Currently, as I do this, I am tracking the line number and entering an index. The index is the row I want to delete. Therefore, every time I read a new row of data, I increase the number of rows. Now when I get the line count, which is the same index, I am not writing data to a temporary file. Now it works, but what if, for example, I work with huge files, and I have to worry about memory limitations. How can I do this with ... file markers? For example .. put the file marker on the line I want to delete. Then delete this line? Or is it too much work?

+3
source share
4 answers

Do not store the file in memory, just read it one line at a time and write it to the temporary file one line at a time, skipping the line that you want to delete.

+2
source

You can use nio to remove the area of ​​the file corresponding to this line.

EDIT added a few tips

By creating FileChanneland using Buffer, you can open the file, delete the desired line by clicking on the contents that appear after.

Unfortunately, I have to admit that my knowledge of nio stops here about ...

+1
source

. , , - , . , , . reset , reset . , , , , ( ), , .

0

Ideally, I would use the ETL tool to do this kind of batch work. Assuming you don’t have access to such a tool, I would recommend the gZipping file first and then read it using java.util.zip .

Here is a good tutorial on how to do this.

Hope this helps!

0
source

Source: https://habr.com/ru/post/1737548/


All Articles