RAII in Java… is resource disposal always so ugly?

后端 未结 5 841
日久生厌
日久生厌 2020-12-05 15:00

I just played with Java file system API, and came down with the following function, used to copy binary files. The original source came from the Web, but I added try/catch/f

5条回答
  •  没有蜡笔的小新
    2020-12-05 15:55

    The try/finally pattern is the correct way to handle streams in most cases for Java 6 and lower.

    Some are advocating silently closing streams. Be careful doing this for these reasons: Java: how not to make a mess of stream handling


    Java 7 introduces try-with-resources:

    /** transcodes text file from one encoding to another */
    public static void transcode(File source, Charset srcEncoding,
                                 File target, Charset tgtEncoding)
                                                                 throws IOException {
        try (InputStream in = new FileInputStream(source);
             Reader reader = new InputStreamReader(in, srcEncoding);
             OutputStream out = new FileOutputStream(target);
             Writer writer = new OutputStreamWriter(out, tgtEncoding)) {
            char[] buffer = new char[1024];
            int r;
            while ((r = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, r);
            }
        }
    }
    

    AutoCloseable types will be automatically closed:

    public class Foo {
      public static void main(String[] args) {
        class CloseTest implements AutoCloseable {
          public void close() {
            System.out.println("Close");
          }
        }
        try (CloseTest closeable = new CloseTest()) {}
      }
    }
    

提交回复
热议问题