Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a line from a file in java

Tags:

java

file-io

Ok, so I'm trying to delete lines from a text file with java. Currently the way I'm doing this, is I'm keep track of a line number and inputting an index. The index is the line I want deleted. So each time I read a new line of data I increment the line count. Now when I reach the line count that is the same index, I dont write the data to the temporary file. Now this works, but what if for example I'm working with huge files and I have to worry about memory restraints. How can I do this with.. file markers? For example.. place the file marker on the line I want to do delete. Then delete that line? Or is that just too much work?

like image 618
dalton conley Avatar asked Feb 14 '26 18:02

dalton conley


1 Answers

Don't keep the file in memory, just read it one line at a time and write it out to the temporary file one line at at a time skipping the line that needs to be deleted.

like image 60
MK. Avatar answered Feb 16 '26 10:02

MK.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!