直接放在catch代码块里
int length = 0;
try {
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
} catch (IOException e1) {
fis.close();
fos.close();
return false;
}
int length = 0;
try {
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
} catch (IOException e1) {
fis.close();
fos.close();
return false;
}
所以,你的
finally{
try {
fis.close();
fos.close();
} catch (IOException e2){
return false;
}
}
可以改成这样:
finally{
if(fis == null || fos == null){
return;
}else {
fis.close();
fos.close();
}
}
int length = 0;
try {
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
}catch (IOException e1) {
...
} finally {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
}
是不是当发生IOException时,fis fos会被系统自动关闭呢?
有这种可能吗?
不管是在catch还是finally里,否则编译都通不过.
建议你增加finnaly来只是用来实现文件流的关闭,其他的什么都不做:
finally {
try {
if(fis!=null) fis.close();
if(fos!=null) fos.close();
} catch(IOException ioe) {
}
}
返回值(因为你的拷贝功能实现与否和文件流是否关闭没有关系)还是在try和catch中返回。
like:
public IOException fileCopy(...){...}
你不想捕获,就应该用抛出:
public boolean fileCopy(...) throws IOException{...}
finally {
try { if(fis!=null) fis.close(); } catch(Exception e){}
try { if(fos!=null) fos.close(); } catch(Exception e){}
}