读书人

关于输入输出流的有关问题!

发布时间: 2012-09-10 22:20:12 作者: rapoo

关于输入输出流的问题!!
package com.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class lianxi {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File a=new File("c:\\wang\\test.xlsx");
try {
FileInputStream in=new FileInputStream(a);
FileOutputStream out=null;
out=new FileOutputStream(new File("c:\\wang\\test1.xlsx"));
byte zhongzhuan[]=new byte[(int)a.length()];
int len;
if((len=in.read(zhongzhuan, 0, zhongzhuan.length))!=-1)
{
out.write(zhongzhuan,0,zhongzhuan.length);
out.flush();
}
out.close();
if(out!=null) {
out.close();
}
if(in!=null) {

in.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
[color=#FF0000][/color]
为什么要加这两句,麻烦大虾帮忙解决一下??

[解决办法]
应该new失败的时候可能是null。

但你写的不好。 因为发生exception时,也许也需要关闭流。
所以一般把关闭写在finally里。

Java code
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();
}
就是多余的了。

读书人网 >J2SE开发

热点推荐