易截截图软件、单文件、免安装、纯绿色、仅160KB

Java解惑4 41域和流

下面的方法将一个文件拷贝到另一个文件,并且被设计为要关闭它所创建的每一个流,即使它碰到I/O错误也要如此。遗憾的是,它并非总是能够做到这一点。为什么不能呢,你如何才能订正它呢?
static void copy(String src, String dest) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) > 0)
out.write(buf, 0, n);
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
这个程序看起来已经面面俱到了。其流域(in和out)被初始化为null,并且新的流一旦被创建,它们马上就被设置为这些流域的新值。对于这些域所引用的流,如果不为空,则finally语句块会将其关闭。即便在拷贝操作引发了一个IOException的情况下,finally语句块也会在方法返回之前执行。出什么错了呢?
问题在finally语句块自身中。close方法也可能会抛出IOException异常。如果这正好发生在in.close被调用之时,那么这个异常就会阻止out.close被调用,从而使输出流仍保持在开放状态。
请注意,该程序违反了谜题36的建议:对close的调用可能会导致finally语句块意外结束。遗憾的是,编译器并不能帮助你发现此问题,因为close方法抛出的异常与read和write抛出的异常类型相同,而其外围方法(copy)声明将传播该异常。
解决方式是将每一个close都包装在一个嵌套的try语句块中。下面的finally语句块的版本可以保证在两个流上都会调用close:
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
// There is nothing we can do if close fails
}
if (out != null)
try {
out.close();
} catch (IOException ex) {
// There is nothing we can do if close fails
}
}
}
从5.0版本开始,你可以对代码进行重构,以利用Closeable接口:
} finally {
closeIgnoringException(in);
closeIgnoringEcception(out);
}
private st


相关文档:

JNA实现Java调用Fortran

在成功实现Java调用C++之后,接下来想到能否通过JNA实现Java调用Fortran,今天试验了一下,还是比较容易的。
网上有一个Java调用F95的例子,但是我考虑不仅要实现F95的调用,还要实现F77的调用,所以费了一些周折。
问题的关键在于F77为过程名自动添加了一个尾部的下划线,所以sub1这个过程,到Java一端,就变成了sub1_, ......

IBM FileNet Content Java API 简介

2008 年 6 月 24 日
原文地址: http://www.ibm.com/developerworks/cn/data/library/techarticles/dm-0806wangys/
本文介绍 IBM FileNet P8 4.0 Platform 提供的 Content Java API。首先对 FileNet P8 Content Engine 和 API 进行概要介绍, 并说明了一些基本概念,随后详细介绍了 FileNet Content Engine提供的基于 EJB ......

java 容器类 小结 troy

JAVA的容器---List,Map,Set
Collection
├List
│├LinkedList
│├ArrayList
│└Vector
│ └Stack
└Set
Map
├Hashtable
├HashMap
└WeakHashMap
Collection接口
  Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements)。一些 Collection允许相 ......

java计算程序用时


Java代码
long startTime=System.currentTimeMillis();   //获取开始时间  
doSomeThing(); //测试的代码段  
long endTime=System.currentTimeMillis(); //获取结束时间  
System.out.println("程序运行时间: "+(endTime-startTime)+"ms");  
第二种是以纳秒为 ......

Java Native Method[还没来得及翻译]

The goal for this chapter is to introduce you to Java's native methods. If you are new to Java, you may not know what native methods are, and even if you are an experienced Java developer, you may not have had a reason to learn more about native methods. At the conclusion of this chapter you should ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号