使用Java ByteArrayOutputstream压缩文件

时间:2014-10-21 09:01:23

标签: java compression bytearrayoutputstream

我正在尝试使用Java ByteArrayOutputstream压缩文件,但是我失败了。如果我将ouputstream更改为FileOutput流,它可以工作。我该怎么做才能使它工作?为什么?

这是我的代码(Sorrry,我的英语太差了):

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.FileUtils;

public class ZipOutputStreamTest {

public static void main(String args[]) throws IOException {
    test1();
    test2();
}

/*this failed, the exported file can't be open*/
public static void test1() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = genZip(baos);
    byte[] bytes = baos.toByteArray();
    FileUtils.writeByteArrayToFile(new File("d:\\test1.zip"), bytes);
    FileOutputStream fos = new FileOutputStream(new File("d:\\test1.zip"));
    for(byte b : bytes){
        fos.write(b);
    }
    fos.close();
    zos.close();
    baos.close();
}

/*this can work*/
public static void test2() throws IOException {
    FileOutputStream fileOutputStream = new FileOutputStream("d:\\test2.zip");
    ZipOutputStream zos = genZip(fileOutputStream);
    zos.close();
    fileOutputStream.close();
}

public static ZipOutputStream genZip(OutputStream os) throws IOException{
    ZipOutputStream zos = new ZipOutputStream(os, Charset.forName("gbk"));
    for(int i=0;i<5;i++){
        ZipEntry entry = new ZipEntry("ab"+i+".txt");
        zos.putNextEntry(entry);
        zos.write("中文asaf".getBytes());
        zos.closeEntry();
        }
        return zos;
    }
}

谢谢!

2 个答案:

答案 0 :(得分:1)

为什么将FileOutputStream与FileUtils.writeByteArrayToFile(...)一起使用?你两次写相同的数据。

删除test1()中的FileOutputStream用法。像这样:

public static void test1() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = genZip(baos);
    zos.close();
    baos.close();

    byte[] bytes = baos.toByteArray();
    FileUtils.writeByteArrayToFile(new File("d:\\test1.zip"), bytes);
}

答案 1 :(得分:0)

I have faced a similar issue.. It got resolved when I added zos.finish();