前言
今天有个宝宝问我,为什么我的代码和你一摸一样,但是一运行就报错。我一看代码,说你踩坑了,你文件操作没有写close()语句。她说,你也没写鸭,怎么你就不报错。我说,这是因为我用了Java7引入的新语法try-with-recources,它会帮我在文件操作结束后自动调用close()方法。
非try-with-resourses写法
正常的文件操作之后,需要调用close()语句,以关闭流,并对缓存区进行冲刷,把缓存区的内容真正的写入磁盘(缓冲区是为了避免频繁的进行磁盘操作,因为磁盘操作是很费时间的)。写法如下:
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(DiskConstant.DISK_FILE, "rw");
randomAccessFile.seek(diskBlockIndex * DiskConstant.BLOCK_SIZE + boffset);
randomAccessFile.write(bytes, offset, length);
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
复制代码
然而,这种写法极其繁琐,包含了大量的模板代码,其中核心代码只有try{}里面的3行。且非常容易忘记在finally里面调用close()导致错误的发生。
try-with-resources写法
这里try()在括号里new的类,只要该类实现了Closeable接口,在try(){}代码块结束后,会自动调用Closeable接口的close()方法。因此,在非特殊情况下,文件操作都应该使用try-with-resources语法,以简化代码,避免漏写close()方法。下面代码等价于上面的非try-with-resources写法,代码行数少了5行。
try (RandomAccessFile randomAccessFile = new RandomAccessFile(DiskConstant.DISK_FILE, "rw")) {
randomAccessFile.seek(diskBlockIndex * DiskConstant.BLOCK_SIZE + boffset);
randomAccessFile.write(bytes, offset, length);
}
复制代码