Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using for loop write lines one by one in file using java [closed]

Tags:

java

file-io

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

like image 656
Piyush Avatar asked Mar 31 '13 06:03

Piyush


People also ask

How do you write multiple lines in a text file in Java?

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.

Can we use for loop in Java?

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.


1 Answers

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();
like image 137
user93353 Avatar answered Sep 28 '22 08:09

user93353