简体   繁体   中英

Java FileUtils: remove specific line from file

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.

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. ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM