我们深知在操作Java流对象后要将流关闭,但往往事情不尽人意,大致有以下几种不能一定将流关闭的写法:
1.在try中关流,而没在finally中关流
[java] view plain copy
1. try {
2. OutputStream out = new FileOutputStream("");
3. // ...操作流代码
4. out.close();
5. } catch (Exception e) {
6. e.printStackTrace();
7. }
正确写法:
[java] view plain copy
1. OutputStream out = null;
2. try {
3. out = new FileOutputStream("");
4. // ...操作流代码
5. } catch (Exception e) {
6. e.printStackTrace();
7. } finally {
8. try {
9. if (out != null) {
10. out.close();
11. }
12. } catch (Exception e) {
13. e.printStackTrace();
14. }
15. }
2.在关闭多个流时因为嫌麻烦将所有关流的代码丢到一个try中
[java] view plain copy
1. OutputStream out = null;
2. OutputStream out2 = null;
3. try {
4. out = new FileOutputStream("");
5. out2 = new FileOutputStream("");
6. // ...操作流代码
7. } catch (Exception e) {
8. e.printStackTrace();
9. } finally {
10. try {
11. if (out != null) {
12. out.close();// 如果此处出现异常,则out2流没有被关闭
13. }
14. if (out2 != null) {
15. out2.close();
16. }
17. } catch (Exception e) {
18. e.printStackTrace();
19. }
20. }
正确写法:
[java] view plain copy
1. OutputStream out = null;
2. OutputStream out2 = null;
3. try {
4. out = new FileOutputStream("");
5. out2 = new FileOutputStream("");
6. // ...操作流代码
7. } catch (Exception e) {
8. e.printStackTrace();
9. } finally {
10. try {
11. if (out != null) {
12. out.close();// 如果此处出现异常,则out2流也会被关闭
13. }
14. } catch (Exception e) {
15. e.printStackTrace();
16. }
17. try {
18. if (out2 != null) {
19. out2.close();
20. }
21. } catch (Exception e) {
22. e.printStackTrace();
23. }
24. }
3.在循环中创建流,在循环外关闭,导致关闭的是最后一个流
[java] view plain copy
1. OutputStream out = null;
2. try {
3. for (int i = 0; i < 10; i++) {
4. out = new FileOutputStream("");
5. // ...操作流代码
6. }
7. } catch (Exception e) {
8. e.printStackTrace();
9. } finally {
10. try {
11. if (out != null) {
12. out.close();
13. }
14. } catch (Exception e) {
15. e.printStackTrace();
16. }
17. }
正确写法:
[java] view plain copy
1. for (int i = 0; i < 10; i++) {
2. OutputStream out = null;
3. try {
4. out = new FileOutputStream("");
5. // ...操作流代码
6. } catch (Exception e) {
7. e.printStackTrace();
8. } finally {
9. try {
10. if (out != null) {
11. out.close();
12. }
13. } catch (Exception e) {
14. e.printStackTrace();
15. }
16. }
17. }
java源码启发:
1. OutputStream out = null;
2. try {
3. out = new FileOutputStream("");
4. // ...操作流代码
5. } catch (Exception e) {
6. e.printStackTrace();
7. } finally {
8. try {
9. if (out != null) {
10. out.close();
11. out = null;//该现象是源码关闭流时出现的,需要验证
12. }
13. } catch (Exception e) {
14. e.printStackTrace();
15. }
16. }