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);
}

but it doesn't work, please give some help for append or PrintWriter method, i have no idea how to use these methods.

i need file output like

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

thanks

Piyush
  • 1,528
  • 2
  • 24
  • 39
  • Which thing doesn't work? Or any error occurs? – Thiha Maung Mar 31 '13 at 06:27
  • possible duplicate of [How do I save a String to a text file using Java?](http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java) – dunni Mar 31 '13 at 14:17

3 Answers3

55

Your code is creating a new file for every line. Pull the file open outside of the for loop.

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();

If you want to use PrintWriter, try this

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

for(i=0;i<10;i++)
{
    f0.println("Result "+ i +" : "+ ans);
}
f0.close();
user93353
  • 13,733
  • 8
  • 60
  • 122
  • 4
    appending '\n' isn't very portable. you should use a buffered writer wrapper then the `newLine();` – Oren Mar 31 '13 at 06:28
3

PrintWriter.printf seems to be the most appropriate

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();
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
-1

Just try this :

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);
}
lokoko
  • 5,785
  • 5
  • 35
  • 68