# BufferedWriter won't work

## Recommended Posts

AlphaCoder    102
import java.io.BufferedWriter;
import java.io.FileWriter;

public class write {
public static void main(String[] args) throws Exception {
BufferedWriter bufferedWriter = null;
bufferedWriter = new BufferedWriter(new FileWriter("yourFile.txt"));
bufferedWriter.write("string");
bufferedWriter.newLine();
bufferedWriter.write("string");
}
}


program runs, creates a file called yourFile.txt the file is empty. it doesn't have the stuff that was supposedly written into it. no matter what i do, i can't bufferedwriter to work.

##### Share on other sites
AlphaCoder    102
Quote:
 Original post by guyver23The reason your code doesn't work is because you are using the write() method in the wrong way. Have a look at the documentation:http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedWriter.html

No I'm not.

The code I've pasted is straight from a guide on BufferedWriter. Every other tutorial/guide I've looked at did it exactly this way.

##### Share on other sites
prh99    520
Considered calling the flush() and close() methods after your three writes. The strings you're writing likely do not fill the buffer enough to cause it write to the file, so you'll need explicitly tell it by call the previously mentioned methods.

import java.io.BufferedWriter;import java.io.FileWriter;public class write {  public static void main(String[] args) throws Exception {    BufferedWriter bufferedWriter = null;    bufferedWriter = new BufferedWriter(new FileWriter("yourFile.txt"));    bufferedWriter.write("string");    bufferedWriter.newLine();    bufferedWriter.write("string");       bufferedWriter.flush();    bufferedWriter.close();  }}

I believe, but I am not entirely sure, that just calling close() does a flush(), so it maybe redundant to call both in this example.

##### Share on other sites
guyver23    181
It seems I was in error; I apologize.