如何在java中删除文本文件的第一行 [英] How to remove first line of a text file in java
本文介绍了如何在java中删除文本文件的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到一种方法来使用java删除文本文件中的第一行文本。想使用扫描仪做到这一点...有没有一个好的方法来做到这一点而不需要tmp文件?
I am trying to find a way to remove the first line of text in a text file using java. Would like to use a scanner to do it...is there a good way to do it without the need of a tmp file?
谢谢。
推荐答案
Scanner fileScanner = new Scanner(myFile);
fileScanner.nextLine();
这将返回文件的第一行文本并丢弃它,因为你没有存储它任何地方。
This will return the first line of text from the file and discard it because you don't store it anywhere.
覆盖现有文件:
FileWriter fileStream = new FileWriter("my/path/for/file.txt");
BufferedWriter out = new BufferedWriter(fileStream);
while(fileScanner.hasNextLine()) {
String next = fileScanner.nextLine();
if(next.equals("\n"))
out.newLine();
else
out.write(next);
out.newLine();
}
out.close();
请注意,您必须捕获并处理一些 IOException
这样。此外,在 while()
循环中需要 if()... else()...
语句保持文本文件中存在任何换行符。
Note that you will have to be catching and handling some IOException
s this way. Also, the if()... else()...
statement is necessary in the while()
loop to keep any line breaks present in your text file.
这篇关于如何在java中删除文本文件的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文