如何删除文本文件的行? [英] How do I delete rows of a text file?
本文介绍了如何删除文本文件的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用Java删除文本文件的前两行?
How can I delete the first two rows of a text file with Java?
推荐答案
这是番石榴解决方案:
public static void removeLines(final File targetFile,
final Charset charSet,
final Collection<Integer> lineNumbers) throws IOException{
final List<String> lines = Files.readLines(targetFile, charSet);
// line numbers need to be sorted in reverse.
// if they are, you can replace everything from Ordering until )){
// with 'lineNumbers){'
for(final Integer lineNumber : Ordering
.natural()
.reverse()
.immutableSortedCopy(lineNumbers)){
lines.remove(lineNumber.intValue());
}
Files.write(Joiner.on('\n').join(lines), targetFile, charSet);
}
是的,整个文件都被读入内存,所以不要试试这个使用庞大的服务器日志文件。
Yes, the entire file is read into memory, so don't try this with huge server log files.
这篇关于如何删除文本文件的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文