public class MyAutoClosableResource implements AutoCloseable {
private String resName;
private int counter;
public MyAutoClosableResource(String resName) {
this.resName = resName;
}
public String read() throws IOException {
counter++;
if (Math.random() > 0.1) {
return "You got lucky to read from " + resName + " for " + counter + " times...";
} else {
throw new IOException("resource不存在哦");
}
}
@Override
public void close() throws Exception {
System.out.println("资源释放了:" + resName);
}
}///try是在哪里用什么方法回收资源的啊这个close就输出啊?
展开
作者回复:
这个例子只是展示实现了AutoCloseable的实例在新的try语句块中创建, Java会调用它的close方法. 后面会又实际的close的例子.