日期:2014-05-20  浏览次数:20706 次

关于ArrayList和集合类做容器存取文件的问题!
//把文件流写入到容器中
ArrayList ls=new ArrayList();
FileInputStream fins=new FileInputStream("D:\\IPMSG.exe");
byte[] ifdata=new byte[1024];
int iflen=0;
while ((fins.read(ifdata))>0) {
ls.add(ifdata);
}
fins.close();

//从容器中取出文件
FileOutputStream fouts=new FileOutputStream("D:\\1.exe");
byte[] wfdata=new byte[1024];
int wflen=0;
for (int i = 0; i <ls.size(); i++) {
fouts.write((byte[])ls.get(i));
}
fouts.flush();
fouts.close();

我想问,为什么这个写法只能存取txt文件,而其他文件写入以后运行的时候显示的是损坏的文件。是什么原因?是我写错了?哪位大侠给指点一下,或者有其他的思路给几个。谢谢了。

------解决方案--------------------
因为你读取文件的方式有问题,在读取文件时已经破坏了文件的完整性,所以造成文件损坏。
byte[] ifdata=new byte[1024];
定义了1024个长度的byte,最后一次读取文件的长度一定小于等于1024,当等于1024时是没有问题的,但是如果长度小于1024,比如只读入100个byte那么就会产生924个多余byte,这是我们不需要的俗称脏数据。
修改方法就是去掉这些脏数据。注意看ls.add(reset(ifdata, iflen));
Java code
    public static void main(String[] args) throws IOException {
        // 把文件流写入到容器中
        ArrayList ls = new ArrayList();
        FileInputStream fins = new FileInputStream("d:/soft/chrome_installer.exe");
        byte[] ifdata = new byte[1024];
        int iflen=0;
        while ((iflen = fins.read(ifdata)) > -1) {
            ls.add(reset(ifdata, iflen));
        }
        fins.close();

        // 从容器中取出文件
        FileOutputStream fouts = new FileOutputStream("c:/1.exe");
        for (int i = 0; i < ls.size(); i++) {
            fouts.write((byte[]) ls.get(i));
        }
        fouts.flush();
        fouts.close();
    }

    public static byte[] reset(byte[] in, int len) {
        byte[] b = new byte[len];
        System.arraycopy(in, 0, b, 0, len);
        return b;
    }