@linux1s1s
2016-02-17T02:50:35.000000Z
字数 1373
阅读 4845
2016-02 Java
先看一下信手拈来的流处理代码
public static void fileOperationBad(String path) {if (!makesureFileExist(path)) {return;}InputStream in = null;OutputStream os = null;try {File f = new File(path);in = new FileInputStream(f);os = new FileOutputStream(f);// ...in.close();os.close();} catch (Exception e) {e.printStackTrace();}}
对上面代码,L2中的判断路径文件是否存在这里暂时忽略掉,重点关注L15-L16关闭流的姿势是否正确,这里是典型的初学者最喜欢的代码风格,也是我们极力不推荐的,为什么不推荐,搞不清楚的话可以自行google,那么稍微有点经验的Java程序员对于关闭流的姿势又是什么呢?
public static void fileOperationNormal(String path) {if (!makesureFileExist(path)) {return;}InputStream in = null;OutputStream os = null;try {File f = new File(path);in = new FileInputStream(f);os = new FileOutputStream(f);// ...} catch (IOException e) {e.printStackTrace();} finally {try {if (in != null) {in.close();}if (os != null) {os.close();}} catch (IOException e) {e.printStackTrace();}}}
上面的代码很小心的在finally块中尝试关闭流,但是这样真的能很完整的关闭两个流吗?如果不能很完整的关闭,那么你能指出来原因吗?仔细观察一下不难发现,其实上面代码还是不能完整的关闭流,那么经验丰富的Java程序员该如何做呢?我们来看看下面的代码风格
public static void fileOperationFine(String path) {if (!makesureFileExist(path)) {return;}InputStream in = null;OutputStream os = null;try {File f = new File(path);in = new FileInputStream(f);os = new FileOutputStream(f);// ...} catch (IOException e) {e.printStackTrace();} finally {closeQuietly(in);closeQuietly(os);}}private static void closeQuietly(Closeable closeable) {try {if (closeable != null) {closeable.close();}} catch (IOException e) {e.printStackTrace();}}
上面的代码明显就是经验丰富的程序员应该有的关闭流的正确姿势,原因不再解释。
