用java修改文本文件的内容并写入新文件
我已经有了基本的代码,但是由于我使用的while循环,我实际上只能将文本文件的最后一行写入新文件。我试图修改testfile.txt中的文本,并将其写入名为mdemarco.txt的新文件。我试图做的修改是在每行前面添加一个行号。有人知道在while循环运行时将while循环的内容写入字符串并将结果字符串输出到mdemarco.txt或类似的东西的方法吗用java修改文本文件的内容并写入新文件,java,text-files,read-write,Java,Text Files,Read Write,我已经有了基本的代码,但是由于我使用的while循环,我实际上只能将文本文件的最后一行写入新文件。我试图修改testfile.txt中的文本,并将其写入名为mdemarco.txt的新文件。我试图做的修改是在每行前面添加一个行号。有人知道在while循环运行时将while循环的内容写入字符串并将结果字符串输出到mdemarco.txt或类似的东西的方法吗 public class Writefile { public static void main(String[] args) throws
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
有人能帮忙吗?字符串变量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);
及
而不是:
while(file.hasNext())
b = (n+". "+s);
非常感谢你!在写字板上工作很好!碰巧你知道为什么它没有在记事本中以新行打印吗?@Michaeldermarko你需要使用\r\n作为新行组合。对于独立于平台的选择,请使用System.getPropertyline.separator。非常感谢您的帮助!谢谢你,伙计!直到我查了一下,我才知道Next和NextLine之间的区别。