【发布时间】:2015-04-05 11:16:17
【问题描述】:
所以我已经有了基本的代码,但是由于我正在使用 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
有人可以帮忙吗?
【问题讨论】:
标签: java text-files read-write