考虑 :
public static void read(String filename) throws IOException {
String charsetName = "UTF-8";
InputStream file = new FileInputStream(filename); // say no problem
InputStreamReader reader = new InputStreamReader(file, charsetName);
BufferedReader buffer = new BufferedReader(reader);
try {
buffer.readLine();
} finally {
try {
buffer.close();
} catch (IOException e) {
// report at least
e.printStackTrace();
}
}
}
如果 new InputStreamReader(file, charsetName)
throws UnsupportedEncodingException
,buffer.close();
则永远不会调用该行。另一种方法是额外的冗长:
InputStream file = new FileInputStream(filename);
try {
InputStreamReader reader = new InputStreamReader(file);
try {
BufferedReader buffer = new BufferedReader(buffer);
try {
buffer.readLine();
} finally {
buffer.close(); // should catch
}
} finally {
reader.close(); // should catch
}
} finally {
file.close(); // should catch
}
并且它不必要地关闭了所有流(虽然output.close();
应该足够了 - 实际上,如果成功,它们中的任何一个都足够了 -请参阅 Skeet 代码中的注释)。
包装构造函数
BufferedReader buffer = new BufferedReader(
new InputStreamReader(new FileInputStream(filename), charsetName));
本质上只是隐藏问题。
请注意,我在这里使用@TomHawtin-tackline 建议的 try-finally 习语- 但更常见的方法是:
public static void read(String filename) throws IOException {
String charsetName = "UTF-8";
InputStream file = null;
InputStreamReader reader = null;
BufferedReader buffer = null;
try {
file = new FileInputStream(filename);
reader = new InputStreamReader(file, charsetName);
buffer = new BufferedReader(reader);
buffer.readLine();
} finally {
try {
if(buffer != null) buffer.close();
} catch (IOException e) {
// report at least
e.printStackTrace();
}
// Rinse and repeat for the rest
}
}
一样尴尬。
问题 :
你会如何处理这个案子?
将 :
public static void read(String filename) throws IOException {
String charsetName = "UTF-8";
InputStream file = new FileInputStream(filename);
try {
InputStreamReader reader = new InputStreamReader(file, charsetName);
BufferedReader buffer = new BufferedReader(reader); // Eclipse warning
buffer.readLine();
// notice that if these were out put streams we SHOULD FLUSH HERE
} finally {
try {
file.close();
} catch (IOException e) {
// report at least
e.printStackTrace();
}
}
}
做 ?换句话说,当有超过 2 个包裹的流时,关闭最里面的流(与通常 要求的相反)将是最干净的解决方案?是否存在装饰器也应该关闭的情况?请参阅此处的示例点。请注意 Eclipse 警告:finally
资源泄漏:“缓冲区”永远不会关闭
日食是对的吗?
这是 Java 6 - 我提醒你,Android 只是 Java 6。尝试一劳永逸地在某些实用程序类中排除 IO 代码