在java中修改文本文件的内容并写入新文件 [英] Modify contents of text file and write to new file in java
问题描述
所以我已经有了基本的代码,但是由于我使用的 while 循环,我真的只能将文本文件的最后一行写入新文件.我正在尝试修改 testfile.txt
中的文本并将其写入名为 mdemarco.txt
的新文件.我试图做的修改是在每行前面添加一个行号.有没有人知道一种方法可以在运行时将 while 循环的内容写入字符串并将结果字符串输出到 mdemarco.txt
或类似的东西?
So I've got the basic code for this however due to the while loop I'm using, I can really only write the last line of the text file to the new file. I'm trying to modify the text from testfile.txt
and write it to a new file named mdemarco.txt
. The modification I'm trying to do is add a line number in front of each line. Does anybody know a way to maybe write the contents of the while loop to a string while it runs and output the resulting string to mdemarco.txt
or anything like that?
public class Writefile
{
public static void main(String[] args) throws IOException
{
try
{
Scanner file = new Scanner(new File("testfile.txt"));
File output = new File("mdemarco.txt");
String s = "";
String b = "";
int n = 0;
while(file.hasNext())
{
s = file.nextLine();
n++;
System.out.println(n+". "+s);
b = (n+". "+s);
}//end while
PrintWriter printer = new PrintWriter(output);
printer.println(b);
printer.close();
}//end try
catch(FileNotFoundException fnfe)
{
System.out.println("Was not able to locate testfile.txt.");
}
}//end main
}//end class
输入文件文本为:
do
re
me
fa
so
la
te
do
我得到的输出只是
8. do
有人可以帮忙吗?
推荐答案
String
变量 b
在循环的每次迭代中都会被覆盖.您想附加到它而不是覆盖它(您可能还想在末尾添加一个换行符):
The String
variable b
is overwriten in each iteration of the loop. You want to append to it instead of overwriting (you may also want to add a newline character at the end):
b += (n + ". " + s + System.getProperty("line.separator"));
更好的是,使用 StringBuilder
来附加输出:
Better yet, use a StringBuilder
to append the output:
StringBuilder b = new StringBuilder();
int n = 0;
while (file.hasNext()) {
s = file.nextLine();
n++;
System.out.println(n + ". " + s);
b.append(n).append(". ").append(s).append(System.getProperty("line.separator"));
}// end while
PrintWriter printer = new PrintWriter(output);
printer.println(b.toString());
这篇关于在java中修改文本文件的内容并写入新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!