stream的关闭问题和try catch finally的问题
原型代码1:
private void writeToFile(String LogfilePath) {
BufferedWriter out = null;
try {
FileWriter filestream = new FileWriter(LogfilePath);
out = new BufferedWriter(filestream); //
Log.i(TAG, "Start to write data");
out.write(listNum.getText().toString()); // line A
out.close();
} catch (IOException e) {
System.out.println("error for " + "file" + ": "
+ e.getMessage());
}
}
调试发现out do not close on exit.
原因: 如果在line A那一行出现exception时,就会直接跳到catch里面去,这样out.close()这一步就走不到. 解决代码如下:
private void writeToFile(String LogfilePath) {
BufferedWriter out = null;
try {
FileWriter filestream = new FileWriter(LogfilePath);
out = new BufferedWriter(filestream);
Log.i(TAG, "Start to write data");
out.write(listNum.getText().toString());
} catch (IOException e) {
System.out.println("error for " + "file" + ": "
+ e.getMessage());
} finally{
if (out != null){
try {
out.close();
} catch (IOException e){
// do nothing
}
}
out = null;
}
}
原型代码2:
在遇到多个stream需要关闭时,我们经常会使用这样的代码:
OutputStream os = null;
InputStream is = null;
FileOutputStream osfile = null;
try {
is = ftpClient.retrieveFileStream(fromFile);
osfile = new FileOutputStream(toFile);
os = new BufferedOutputStream(osfile);
} catch (IOException ee){
// do something
} finally{
try{
if (is != null)
is.close(); // line B
if (osfile != null)
osfile.close(); // line C
if (os != null)
os.close(); // line D
} catch (IOException e){
//do nothing
}
is = null;
osfile = null;
os = null;
}
我们在处理这个关闭流的问题大多是在finally里面执行,但是忽视了一个问题,那就是如果在lineB发生了exception,那么就会走到catch的exception里面,line C和line D就无法关闭,导致这两个流没有关闭成功,下次执行时就会出现双的.
解决的办法就是多写点,虽然长的不是很好看,但是效果到了.性能很重要.
解决代码如下:
OutputStream os = null;
InputStream is = null;
FileOutputStream osfile = null;
try {
is = ftpClient.retrieveFileStream(fromFile);
osfile = new FileOutputStream(toFile);
os = new BufferedOutputStream(osfile);
} catch (IOException ee){
// do something
} finally{
if (is != null){
try{
is.close();
} catch (IOException e){
//do nothing
}
}
if (osfile != null){
try{
osfile.close();
} catch (IOException e){
// do nothing
}
}
if (os != null){
try{
os.close();
} catch (IOException e){
// do nothing
}
}
is = null;
osfile = null;
os = null;
}