其他
可不可以不用再写 finally ?
你关注的就是我关心的!
1、引言
2、繁荣表面下的隐患
3、说好的奇技淫巧呢?
4、万能的 try-with-source?
public abstract class OutputStream implements Closeable, Flushable {}
public class GZIPOutputStream extends DeflaterOutputStream {}
public class DeflaterOutputStream extends FilterOutputStream {}
public class FilterOutputStream extends OutputStream {}
public abstract class OutputStream implements Closeable, Flushable {}
5、构造可自动释放资源的类
public void work() {
System.out.println("开始工作");
}
@Override
public void close() throws IOException {
System.out.println("自动释放资源");
}
}
public static void main(String[] args) throws IOException {
try (ImageStream is = new ImageStream()) {
is.work();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
6、值得注意的地方
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new FileOutputStream(createdFile));
OutputStreamWriter osw = new OutputStreamWriter(gzipOutputStream);
BufferedWriter bw = new BufferedWriter(osw)
) {
// ...
} catch (Exception ex) {
//...
}
if (!closed) {
finish();
if (usesDefaultDeflater)
def.end();
out.close();
closed = true;
}
}
public void close() throws IOException {
if (!closed) {
finish();
if (usesDefaultDeflater)
def.end();
out.close();
closed = true;
}
}
finish( ) out.close( )
OutputStream out = new FileOutputStream(createdFile);
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(out);
OutputStreamWriter osw = new OutputStreamWriter(gzipOutputStream);
BufferedWriter bw = new BufferedWriter(osw)
) {
// ...
} catch (Exception ex) {
//...
}
7、尾声
软件开发不能只关注功能实现,需要时刻保持一颗敬畏的心; 使用 try-with-source 语法糖确实可以帮助我们精简代码并且弱化资源释放的存在感; 软件编程没有银弹,在了解并尝试使用新技术的时候,不仅仅要看到它的优势,也要尝试去发现繁荣背后的隐患,避免踩坑啊;