2015-04-05 46 views
0

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

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 

有人能帮忙吗?

回答

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

非常感谢!在写字板中正常工作! – 2015-04-05 11:26:11

+0

偶然你知道它为什么不在记事本中以新行打印吗? – 2015-04-05 11:32:38

+0

@MichaelDeMarco您需要使用'\ r \ n'作为新的组合。对于平台无关的选择,使用'System.getProperty(“line.separator”)'。 – manouti 2015-04-05 11:37:16

0

变化它到b += (n+". "+s);

+0

非常感谢! – 2015-04-05 11:33:14

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 
+0

非常感谢! – 2015-04-05 11:34:06

0

试试这个:

while(file.hasNextLine()) 

代替:

while(file.hasNext()) 

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

代替:

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

非常感谢你!直到我刚刚查找它时,我才知道Next()和NextLine()之间的区别。 – 2015-04-05 11:33:46

相关问题