简体   繁体   English

Java FileUtils:从文件中删除特定行

[英]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 ? 如何使用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. 您可以使用同一库的lineIterator函数。

  • Get the Line Iterator of the file 获取文件的行迭代器
  • Iterate over the lineIterator and write it to the temporary file. 遍历lineIterator并将其写入临时文件。
  • 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) 关闭两个文件(如果有例外,请处理。最好也使用final)
  • 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. fyi,Iterator延迟加载到内存中,并在调用next时删除对上一行的引用。 [@Obicere : Also, I can not comment directly to the question but loading all the lines to memory does not like a good idea. [@Obicere:另外,我不能直接对这个问题发表评论,但是将所有行加载到内存中并不是一个好主意。 ] ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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