using for loop write lines one by one in file using java
1 2 3 4 5 6 | for(i=0;i<10;i++){ String output = output +"Result"+ i +" :"+ ans +" "; //ans from other logic FileWriter f0 = new FileWriter("output.txt"); f0.write(output); } |
但它不起作用,
请为
我需要文件输出
1 2 3 4 5 6 7 8 | Result 1 : 45 //here 45 is ans Result 2 : 564856 Result 3 : 879 . . . . Result 10 : 564 |
谢谢
您的代码正在为每一行创建一个新文件。 将文件拉出for循环外部。
1 2 3 4 5 6 7 8 9 10 | 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(); |
如果要使用
1 2 3 4 5 6 7 | PrintWriter f0 = new PrintWriter(new FileWriter("output.txt")); for(i=0;i<10;i++) { f0.println("Result"+ i +" :"+ ans); } f0.close(); |
PrintWriter.printf似乎是最合适的
1 2 3 4 5 | 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 2 3 4 5 6 | 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); } |