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

时间:2015-04-05 11:16:18

标签: java text-files read-write

所以我已经得到了这个的基本代码,但是由于我使用的while循环,我实际上只能将文本文件的最后一行写入新文件。我尝试修改testfile.txt中的文本并将其写入名为mdemarco.txt的新文件。我试图做的修改是在每行前面添加一个行号。有没有人知道如何在运行时将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

有人可以帮忙吗?

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

试试这个:

while(file.hasNextLine())

而不是:

while(file.hasNext())

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

而不是:

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