I was testing out writing to files with this code:
package files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args)
{
try
{
try
{
File f = new File("filetest1.txt");
FileWriter fWrite = new FileWriter(f);
BufferedWriter fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
}
catch(FileNotFoundException e)
{
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
}
}
catch(IOException e)
{
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
Nothing happens when it is executed. "This is a test!" is not written, nor the StackTrace or the "A/An [exception] occurred!"... I don't know what's causing the problem. I have fileTest1.txt in the package right under the file...
A
BufferedWriter
does just that, it buffers the output before it is written to the destination. This can make theBufferedWriter
faster to use as it doesn't have to write to a slow destination, like a disk or socket, straight away.The contents will be written when the internal buffer is to full, you
flush
theWriter
orclose
the writerRemember, if you open it, you should close it...
For example...
If you are using Java 7, you may like to take a look at try-with-resources
After
you have to
flush()
the writer. To avoid leaking of resources you should alsoclose()
the writer (which automatically flushes it).So you need to add:
You must call
close()
or at leastflush()
on the writer in order for the buffer to be really written to the file.Use
BufferedWriter.flush()
andBufferedWriter.close()
. Additional info here http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html