file writer doesn't work

后端 未结 5 440
野性不改
野性不改 2020-12-19 14:28

I use a FileWriter and a BufferWriter to write in a file. The file \"test.txt\" is created but nothing is written inside.

The file should be written in the ActionEve

5条回答
  •  甜味超标
    2020-12-19 15:29

    Here,

    try 
    {
        FileWriter fw = new FileWriter("test.txt");
                BufferedWriter out = new BufferedWriter(fw);
                out.write("aString");
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
    

    You wrapped it in a BufferedWriter which has a default buffer size of 8KB. So as long as you don't write more than 8KB and don't flush/close it, then it won't appear in the target file.

    You need to close the writer when you're done with it. This will flush any buffers and release any locks on the file. The normal idiom is to close it in the finally block of the very same try block as where it was been created. This way you guarantee that it's also closed in case of exceptions, hereby preventing resource leaking and forever locked files.

    Writer writer = null;
    
    try {
        writer = new BufferedWriter(new FileWriter("test.txt"));
        writer.write("aString");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (writer != null) try { writer.close(); } catch (IOException ignore) {}
    }
    

    Alternatively, if you're already on Java 7, then you can also use the new try-with-resources statement. It'll automatically close the resource when you leave the try block, resulting in less boilerplate code.

    try (Writer writer = new BufferedWriter(new FileWriter("test.txt"))) {
        writer.write("aString");
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    By the way, I'd work on exception handling as well. Rather display the enduser some sensible error message instead of plain printing it to the stdout and ignoring it further.

提交回复
热议问题