修改文本文件的内容并写入 java 中的新文件

Modify contents of text file and write to new file in java

所以我已经有了基本代码,但是由于我使用的是 while 循环,我实际上只能将文本文件的最后一行写入新文件。我正在尝试修改 testfile.txt 中的文本并将其写入名为 mdemarco.txt 的新文件。我要做的修改是在每行前面添加一个行号。有人知道一种方法可以在 while 循环运行时将 while 循环的内容写入字符串并将结果字符串输出到 mdemarco.txt 或类似的东西吗?

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 在循环的每次迭代中被覆盖。你想附加而不是覆盖它(你可能还想在末尾添加一个换行符):

b += (n + ". " + s + System.getProperty("line.separator"));

更好的是,使用 StringBuilder 附加输出:

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());

改为b += (n+". "+s);

您每行文字的内容没有保存。因此只有最后一行显示在输出文件中。请试试这个:

public static void main(String[] args) throws IOException {
    try {
        Scanner file = new Scanner(new File("src/testfile.txt"));
        File output = new File("src/mdemarco.txt");
        String s = "";
        String b = "";
        int n = 0;
        while (file.hasNext()) {
            s = file.nextLine();
            n++;
            System.out.println(n + ". " + s);

            //save your content here
            b = b + "\n" + (n + ". " + s);
            //end save your content

        }// 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 m

试试这个:

while(file.hasNextLine())

而不是:

while(file.hasNext())

b += (n+". "+s + "\n");

而不是:

b = (n+". "+s);