Is it safe to use Apache commons-io IOUtils.closeQuietly?

前端 未结 4 398
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 05:42

Is this code

    BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"));
    try {
        bw.write(\"test\");
    } finally {
        IOUtils         


        
4条回答
  •  不思量自难忘°
    2020-12-24 06:22

    Yes, it's safe to use it but only for Java6 and lower. From Java7, you should user try-with-resource.

    It will eliminate much of the boilerplate code you have and the need to use IOUtils.closeQuietly.

    Now, you example:

        BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"));
        try {
            bw.write("test");
        } finally {
            IOUtils.closeQuietly(bw);
        }
    

    Can be written as:

       try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) {
           bw.write("test");
       }
    

    It's important to note that in order to use the try-with-resource approach, your resource need to implement a new interface called java.lang.AutoCloseable that was introduced in Java 7.

    Also, you can include a number of resources in a try-with-resource block, just separate them with ;

       try (
           BufferedWriter bw1 = new BufferedWriter(new FileWriter("test1.txt"));
           BufferedWriter bw2 = new BufferedWriter(new FileWriter("test2.txt"))
       ) {
           // Do something useful with those 2 buffers!
       }   // bw1 and bw2 will be closed in any case
    

提交回复
热议问题