Vijay
Vijay

Reputation: 54

Cannot write into a file in java as it is printing using System.out.println

File output=new File("C:\\\\MDU-1617-CSJ0098\\\\web\\\\products.txt");
BufferedWriter writer1 = new BufferedWriter(new FileWriter(output));               
while(q_set2.next()) {
    String s = String.valueOf(q_set2.getInt(1));
    System.out.print(s);
    writer1.write(s);
    writer1.newLine();
}

and the ouput is run: 123456BUILD SUCCESSFUL (total time: 0 seconds)

But in file there is no data

Upvotes: 0

Views: 227

Answers (2)

Raman Sahasi
Raman Sahasi

Reputation: 31891

When you call writer1.write(s), you're not actually printing anything in your file, you're gathering data into memory. Once you've gathered all the data, you can write all of it at once into your file by calling flush().

This is because writing into a file is a costly operation, so BufferedWriter is designed in such a way that that it facilitates writing all data at once instead of writing it in chunks.

That's why you need to flush the stream.

Docs

public void flush() throws IOException

Flushes the stream.

Now eiter you can...

  1. Call flush() method or
  2. close the stream. This will automatically call flush() method.

.

File output=new File("C:\\\\MDU-1617-CSJ0098\\\\web\\\\products.txt");
         BufferedWriter writer1 = new BufferedWriter(new FileWriter(output));               

while(q_set2.next())  {
    String s=String.valueOf(q_set2.getInt(1));
    System.out.print(s);
    writer1.write(s);
    writer1.newLine();
}

writer1.flush(); // or writer1.close();

Upvotes: 0

Darshan Mehta
Darshan Mehta

Reputation: 30839

This is what the write method does:

Ordinarily this method stores characters from the given array into this stream's buffer, flushing the buffer to the underlying stream as needed.

So, it writes to buffer rather than directly writing to file. To make the buffer flush, you need to either call flush or close method, e.g.:

File output = new File("C:\\\\MDU-1617-CSJ0098\\\\web\\\\products.txt");
BufferedWriter writer1 = new BufferedWriter(new FileWriter(output));
while (q_set2.next()) {
    String s = String.valueOf(q_set2.getInt(1));
    System.out.print(s);
    writer1.write(s);
    writer1.newLine();
}
writer1.close();

close() calls flush() internally and hence, you don't need to call flush() explicitly in this case (here's the Javadoc).

Upvotes: 3

Related Questions