JAVA高效编程五(资源关闭)
普通码农 VS 风骚码农
垃圾回收与物理资源释放
传统方式关闭流资源
/**
* JDK7之前的文件拷贝功能
*/
public class FileCopyTest {
@Test
public void copyFile() {
/**
* 1. 创建输入/输出流
* 2. 执行文件拷贝,读取文件内容,写入到另一个文件中
* 3. **关闭文件流资源**
*/
// 定义输入路径和输出路径
String originalUrl = "lib/FileCopyTest.java";
String targetUrl = "targetTest/target.txt";
// 声明文件输入流,文件输出流
FileInputStream originalFileInputStream = null;
FileOutputStream targetFileOutputStream = null;
try {
// 实例化文件流对象
originalFileInputStream =
new FileInputStream(originalUrl);
targetFileOutputStream =
new FileOutputStream(targetUrl);
// 读取的字节信息
int content;
// 迭代,读取/写入字节
while ((content = originalFileInputStream.read()) != -1) {
targetFileOutputStream.write(content);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流资源
if (targetFileOutputStream != null) {
try {
targetFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (originalFileInputStream != null) {
try {
originalFileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
TWR方式关闭流资源
/**
* 基于JDK7之后,实现正确关闭流资源方法
* try - with - resource,在try()方法体内声明物理资源
*/
public class NewFileCopyTest {
@Test
public void copyFile() {
// 先定义输入/输出路径
String originalUrl = "lib/NewFileCopyTest.java";
String targetUrl = "targetTest/new.txt";
// 初始化输入/输出流对象
try (
FileInputStream originalFileInputStream =
new FileInputStream(originalUrl);
FileOutputStream targetFileOutputStream =
new FileOutputStream(targetUrl);
) {
int content;
// 迭代,拷贝数据
while ((content = originalFileInputStream.read()) != -1) {
targetFileOutputStream.write(content);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TWR进阶与特殊情况
直接调用socket的InputStream和outputStream会导致整个socket的关闭,正确的方式应该是调用socket的shutdownInput和shutdownOutput方法来关闭,只关闭流,不关闭链接