开发者

writing to a file problem [duplicate]

This question already has answers here: BufferedWriter not writing everything to its output file (8 answers) Closed 8 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜