问题
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;
}
}
Thanks!
回答1:
Why are you using FileOutputStream together with FileUtils.writeByteArrayToFile(...)? You write same data twice.
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);
}
回答2:
I have faced a similar issue.. It got resolved when I added zos.finish();
来源:https://stackoverflow.com/questions/26482779/compress-file-with-java-bytearrayoutputstream