用Java ByteArrayOutputstream压缩文件 [英] compress file with Java ByteArrayOutputstream

查看:240
本文介绍了用Java ByteArrayOutputstream压缩文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to compress file with Java ByteArrayOutputstream,but I failed.If I change the ouputstream to FileOutput stream,it can work.What should I do to make it work?and why?

这是我的代码(抱歉,我的英语很差):

Here is my code(Sorrry,my english is so poor):

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;
    }
}

谢谢!

推荐答案

为什么要同时使用FileOutputStream和FileUtils.writeByteArrayToFile(...)?您两次写入相同的数据。

Why are you using FileOutputStream together with FileUtils.writeByteArrayToFile(...)? You write same data twice.

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

Remove FileOutputStream usage in test1(). Something like this:

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);
}

这篇关于用Java ByteArrayOutputstream压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆