1

How can I delete a specific line (by index) from a text file with the class org.apache.commons.io.FileUtils?

The index of the line to be deleted already know him, so I need some method that I delete a specific line from a file.

Enzo
  • 597
  • 1
  • 8
  • 22
  • 1
    Have you read: [Find a line in a file and remove](http://stackoverflow.com/questions/1377279/java-find-a-line-in-a-file-and-remove) ? – Obicere Apr 13 '14 at 17:25
  • If you really wish to use the Apache FileUtils, you could use the `lineIterator(File)` method, add those lines to a `Collection`, remove the `ith` line, then use the `writeLines(File, Collection>)` function. – Obicere Apr 13 '14 at 17:29

1 Answers1

0

You can use lineIterator function of the same library.

  • Get the Line Iterator of the file
  • Iterate over the lineIterator and write it to the temporary file.
  • Maintain the index of the current iteration. If in the above step, the line number matches the number you want to skip, dont write it to temporary file.
  • Close both file (handle the case if you exceptions. you may want to use finally as well)
  • delete old file.
  • rename the temporary file to new file

fyi, Iterator loads lazily into memory and drops reference to previous line when next is called. [@Obicere : Also, I can not comment directly to the question but loading all the lines to memory does not like a good idea. ]