您的浏览器过于古老 & 陈旧。为了更好的访问体验, 请 升级你的浏览器
Ready 发布于2013年01月23日 01:38

原创 Java SE 7新特性:try-with-resources语句

2044 次浏览 读完需要≈ 5 分钟

内容目录

Java SE 7中新增了try-with-resources语句。try-with-resources语句是一个声明了一个或多个资源的try语句。这里的一个资源指的是在使用完成后必须关闭释放的对象。try-with-resources语句可以确保在该语句执行之后关闭每个资源。所有实现了java.lang.AutoCloseable接口的对象均可以作为资源在try-with-resources语句中使用(java.io.Closeable是其子接口,因此也支持)。

在Java SE 7之前,为了确保资源被关闭,你可能会编写如下代码:

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
	BufferedReader br = new BufferedReader(new FileReader(path));
	try {
		return br.readLine();
	} finally {
		if (br != null) br.close();
	}
}

不过,在Java SE 7中,你可以用下面的代码来替换上面的代码了:

static String readFirstLineFromFile(String path) throws IOException {
	try (BufferedReader br = new BufferedReader(new FileReader(path))) {
		return br.readLine();
	}
}

你也可以同时声明多个资源:

public static void writeToFileZipFileContents(String zipFileName, String outputFileName) throws java.io.IOException {

	java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");
	java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);
	try (
		//声明两个资源
		java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
		java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
	) {
		//这里是自行编写的代码
	}
}

值得注意的是:在上面的try-with-resources语句执行完毕后,系统先关闭释放writer,再关闭释放zf。也就是说,try-with-resources语句中资源的关闭释放顺序和它们创建的顺序相反。

  • CodePlayer技术交流群1
  • CodePlayer技术交流群2

0 条评论

撰写评论

打开导航菜单