我正在尝试使用 Java ByteArrayOutputstream 压缩文件,但我失败了。如果我将输出流更改为 FileOutput 流,它可以工作。我应该怎么做才能让它工作?为什么?
这是我的代码(对不起,我的英语太差了):
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;
}
}
谢谢!