所以我已经得到了基本代码,但由于我使用的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
有人能帮忙吗?
非常感谢!在写字板中正常工作! – 2015-04-05 11:26:11
偶然你知道它为什么不在记事本中以新行打印吗? – 2015-04-05 11:32:38
@MichaelDeMarco您需要使用'\ r \ n'作为新的组合。对于平台无关的选择,使用'System.getProperty(“line.separator”)'。 – manouti 2015-04-05 11:37:16