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

2

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

appending '\n' isn't very portable. you should use a buffered writer wrapper then the newLine();
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();

Comments

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

2 Comments

I don't see newLine() method in the API
I don't see also.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.