Sign in to follow this  
AlphaCoder

BufferedWriter won't work

Recommended Posts

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 this post


Link to post
Share on other sites
Quote:
Original post by guyver23
The 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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this