When to use which Writer subclass in Java; common practices

后端 未结 4 741
执念已碎
执念已碎 2021-02-07 03:40

I have always been slightly confused with the amount of different IO implementations in Java, and now that I am completely stuck in my project development, I was taking my time

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-07 03:43

    The java.io classes generally follow the Decorator pattern. So, while PrintWriter does not have the specific constructor you might want, it does have a constructor that takes another Writer, so you can do something like the following:

    FileOutputStream fos = null;
    try
    {
        fos = new FileOutputStream("foo.txt");
        PrintWriter out = new PrintWriter(
                              new BufferedWriter(
                                  new OutputStreamWriter(fos, "UTF-8")));
        // do what you want to do
        out.flush();
        out.close();
    }
    finally
    {
        // quietly close the FileOutputStream (see Jakarta Commons IOUtils)
    }
    

    As a general usage note, you always want to wrap a low-level Writer (eg FileWriter or OutputStreamWriter) in a BufferedWriter, to minimize actual IO operations. However, this means that you need to explicitly flush and close the outermost Writer, to ensure that all content is written.

    And then you need to close the low-level Writer in a finally block, to ensure that you don't leak resources.

    Edit:

    Looking at MForster's answer made me take another look at the API for FileWriter. And I realized that it doesn't take an explicit character set, which is a Very Bad Thing. So I've edited my code snippet to use a FileOutputStream wrapped by an OutputStreamWriter that takes an explicit character set.

提交回复
热议问题