使用Java编写for循环,逐行将内容写入文件。

21
for(i=0;i<10;i++){
    String output = output + "Result "+ i +" : "+ ans +"\n";   //ans from other logic
    FileWriter f0 = new FileWriter("output.txt");
    f0.write(output);
}

但它不起作用,请求一些有关appendPrintWriter方法的帮助,我不知道如何使用这些方法。

我需要像文件输出那样的输出。

Result 1 : 45           //here 45 is ans
Result 2 : 564856
Result 3 : 879
.
.
.
.
Result 10 : 564

谢谢


哪个东西不起作用?或者出现了任何错误? - Thiha Maung
3个回答

55

你的代码每一行都创建了一个新文件。在for循环外面打开文件。

FileWriter f0 = new FileWriter("output.txt");

String newLine = System.getProperty("line.separator");


for(i=0;i<10;i++)
{
    f0.write("Result "+ i +" : "+ ans + newLine);
}
f0.close();

如果你想使用 PrintWriter,可以尝试这个方法。

PrintWriter f0 = new PrintWriter(new FileWriter("output.txt"));

for(i=0;i<10;i++)
{
    f0.println("Result "+ i +" : "+ ans);
}
f0.close();

4
添加'\n'不是很通用。你应该使用带缓冲的写入器包装器,然后调用newLine(); - Oren

3
打印写入器(PrintWriter)中的printf似乎是最合适的选择。
PrintWriter pw = new PrintWriter(new FileWriter("output.txt"));
    for (int i = 0; i < 10; i++) {
        pw.printf("Result %d : %s %n",  i, ans);
    }
    pw.close();

-1

只需尝试这个:

FileWriter f0 = new FileWriter("output.txt");
for(i=0;i<10;i++){
    f0.newLine();
    String output = output + "Result "+ i +" : "+ ans;   //ans from other logic
    f0.append(output);
}

1
我在API中没有看到newLine()方法。 - java_enthu
我也看不到。 - Kirill Ch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接