日期:2014-05-20 浏览次数:20939 次
public static void main(String[] args) { // TODO Auto-generated method stub File file = new File("c:\\wang\\test.xlsx"); FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(file); out = new FileOutputStream(new File("c:\\wang\\test1.xlsx")); byte zhongzhuan[] = new byte[(int) file.length()]; int len; if ((len = in.read(zhongzhuan, 0, zhongzhuan.length)) != -1) { out.write(zhongzhuan, 0, len); out.flush(); } out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
------解决方案--------------------
防止NullPointException
一般
FileInputStream in=null;
try{
...
in = new ...//如果这里之前出现异常,则in = null
...
}catch(Exception e){
...
}finally{
if(in!=null){//这里防止出现异常时in为null
in.close();
}
}
------解决方案--------------------
那两句在那位置是有问题的,源代码写得不好。
out.close();
if(out!=null) {
out.close();
}
在没异常情况下,这样会重复关闭。
if(out!=null) {
out.close();
}
就是多余的了。