java流如何关闭
关闭Java流的正确方法
在Java中,流(Stream)包括输入流(InputStream)、输出流(OutputStream)以及它们的子类(如FileInputStream、BufferedReader等)。正确关闭流可以避免资源泄漏和潜在的性能问题。
使用try-with-resources语句
Java 7引入的try-with-resources语法是最推荐的方式,它能自动关闭实现了AutoCloseable接口的资源。
try (InputStream inputStream = new FileInputStream("file.txt");
OutputStream outputStream = new FileOutputStream("output.txt")) {
// 使用流进行操作
} catch (IOException e) {
e.printStackTrace();
}
手动关闭流
在Java 7之前的版本中,需要在finally块中手动关闭流,确保资源被释放。
InputStream inputStream = null;
try {
inputStream = new FileInputStream("file.txt");
// 使用流进行操作
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
关闭多个流的注意事项
当需要关闭多个流时,应分别关闭每个流,避免因某个流关闭失败导致其他流未关闭。
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream("file.txt");
outputStream = new FileOutputStream("output.txt");
// 使用流进行操作
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用工具类关闭流
可以编写工具类来简化关闭流的操作,减少重复代码。
public class StreamUtils {
public static void close(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
调用方式:
InputStream inputStream = null;
try {
inputStream = new FileInputStream("file.txt");
// 使用流进行操作
} catch (IOException e) {
e.printStackTrace();
} finally {
StreamUtils.close(inputStream);
}
处理链式流
当使用链式流(如BufferedReader包装FileReader)时,只需关闭最外层的流,内层流会自动关闭。

try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
// 使用流进行操作
} catch (IOException e) {
e.printStackTrace();
}
注意事项
- 关闭流时可能会抛出IOException,需要进行捕获处理。
- 确保在关闭流之前检查流是否为null,避免NullPointerException。
- 在关闭流后,避免再次使用该流,否则会抛出StreamClosedException。






