writing to a file problem [duplicate]
I am using this code to write to a file i开发者_开发知识库n java. it has always worked and I am 100% sure its right. But still the file does not get written. I don't even get an error.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class writetofile {
public static void main(String [] args){
FileWriter fw;
try {
fw = new FileWriter("testfile.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("this is test");
bw.write("this is test");
bw.write("this is test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Could it be some other problem?
You are not calling the close()
method on the BufferedWriter
object. That means the buffers never get flushed. Add bw.close()
after your last bw.write()
statements.
try fw.flush()
and fw.close()
You need to flush the buffer and you should close the file as well:
try {
fw = new FileWriter("/tmp/testfile.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("this is test");
bw.write("this is test");
bw.write("this is test");
bw.flush();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Also you should handle the IOException from the actual file writing separately from the file closing so you won't leave the file descriptor opened at the end:
FileWriter fw = null;
try {
fw = new FileWriter("/tmp/testfile.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("this is test");
bw.write("this is test");
bw.write("this is test");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Make sure you call bw.close()
before your method exits. If the buffer doesn't get flushed your file wont get written.
Try closing the stream with sw.close()
or the data may still be cached and not actually written to disk.
精彩评论