如何关闭 Java 中的嵌套 I/O 流
How to close nested I/O streams in Java
我有以下代码:
try{
fileOutputStream = new FileOutputStream(downloadFile1);
outputStream1 = new BufferedOutputStream(fileOutputStream);
boolean success = ftpclient.retrieveFile(completePath.get(i), outputStream1);
if (success) {
System.out.println(completePath.get(1)+" downloaded!");
}
}finally {
if (outputStream1!=null) outputStream1.close();
if(fileOutputStream!=null) fileOutputStream.close();
}
IntelliJ 给出错误提示 FileOutputStream 也需要关闭。
而如果我在 finally 块中更改流关闭顺序
finally {
if(fileOutputStream!=null) fileOutputStream.close();
if (outputStream1!=null) outputStream1.close();
}
然后没有错误,但是由于提前关闭了流,所以文件没有完全下载。
有人可以建议正确的方法吗?
BufferedOutputStream(继承自 FilterOutputStream)close method 的文档说
The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.
所以IntelliJ显然是错误的。如果有疑问请相信文档,而不是 IDE 的警告 - 它们是警告而不是错误是有原因的。
也就是说,您应该使用 try-with-resources 语句。
而且您也不需要中间变量,您可以构造 FOS 并立即将其作为参数传递给 BOS 构造函数。
你应该使用 try-with-resources:
private static void printFileJava7() throws IOException {
try( FileInputStream input = new FileInputStream("file.txt");
BufferedInputStream bufferedInput = new BufferedInputStream(input)
) {
int data = bufferedInput.read();
while(data != -1){
System.out.print((char) data);
data = bufferedInput.read();
}
}
参见:
我有以下代码:
try{
fileOutputStream = new FileOutputStream(downloadFile1);
outputStream1 = new BufferedOutputStream(fileOutputStream);
boolean success = ftpclient.retrieveFile(completePath.get(i), outputStream1);
if (success) {
System.out.println(completePath.get(1)+" downloaded!");
}
}finally {
if (outputStream1!=null) outputStream1.close();
if(fileOutputStream!=null) fileOutputStream.close();
}
IntelliJ 给出错误提示 FileOutputStream 也需要关闭。
而如果我在 finally 块中更改流关闭顺序
finally {
if(fileOutputStream!=null) fileOutputStream.close();
if (outputStream1!=null) outputStream1.close();
}
然后没有错误,但是由于提前关闭了流,所以文件没有完全下载。
有人可以建议正确的方法吗?
BufferedOutputStream(继承自 FilterOutputStream)close method 的文档说
The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.
所以IntelliJ显然是错误的。如果有疑问请相信文档,而不是 IDE 的警告 - 它们是警告而不是错误是有原因的。
也就是说,您应该使用 try-with-resources 语句。
而且您也不需要中间变量,您可以构造 FOS 并立即将其作为参数传递给 BOS 构造函数。
你应该使用 try-with-resources:
private static void printFileJava7() throws IOException {
try( FileInputStream input = new FileInputStream("file.txt");
BufferedInputStream bufferedInput = new BufferedInputStream(input)
) {
int data = bufferedInput.read();
while(data != -1){
System.out.print((char) data);
data = bufferedInput.read();
}
}
参见: