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
boolean append = true; String filename = "/path/to/file"; BufferedWriter writer = new BufferedWriter(new FileWriter(filename, append)); // OR: BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append))); writer. write(line1); writer. newLine(); writer.
Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With