【发布时间】:2014-04-18 05:18:23
【问题描述】:
我正在使用以下独立类在压缩之前计算压缩文件的大小。 我正在使用 0 级压缩,但我仍然得到几个字节的差异。 你能帮我弄个确切的尺寸吗?
我们将不胜感激。
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FilenameUtils;
public class zipcode {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
CRC32 crc = new CRC32();
byte[] b = new byte[1024];
File file = new File("/Users/Lab/Desktop/ABC.xlsx");
FileInputStream in = new FileInputStream(file);
crc.reset();
// out put file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/Users/Lab/Desktop/ABC.zip"));
// name the file inside the zip file
ZipEntry entry = new ZipEntry("ABC.xlsx");
entry.setMethod(ZipEntry.DEFLATED);
entry.setCompressedSize(file.length());
entry.setSize(file.length());
entry.setCrc(crc.getValue());
out.setMethod(ZipOutputStream.DEFLATED);
out.setLevel(0);
//entry.setCompressedSize(in.available());
//entry.setSize(in.available());
//entry.setCrc(crc.getValue());
out.putNextEntry(entry);
// buffer size
int count;
while ((count = in.read(b)) > 0) {
System.out.println();
out.write(b, 0, count);
}
out.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
【问题讨论】:
-
我不明白你在做什么。鉴于您必须完成大部分工作才能获得估算值,为什么不直接压缩文件?
-
我必须将文件上传到服务器并即时压缩文件。但为此,我需要在上传之前获取确切的文件大小。我正在尝试的方式,我得到压缩文件和实际文件的几个字节差异。
-
我需要在实际压缩之前获得确切的压缩文件大小。我不希望文件被压缩,但需要它们将它们存储在一个 zip 文件中。所以,我正在尝试 DEFLATED 和 STORED 选项。但是,我尝试的方式是,压缩文件和实际文件的字节差异很小。