请教:关于java中的压缩处理

dasai 2002-05-24 11:40:04
各位大虾,小弟现在在java中压缩文件时遇到如下问题:
当我使用GZIPOutputStream时,生成.gz文件没问题,但里面的文件没有后缀,怎么解决呢??
当我使用ZipOutputStream时,生成.zip文件没问题,但解开时,包含了我在压缩时提供的全路径,造成了压缩文件反而比原文件更大,怎么解决??
还有,这两个类都是压缩的类,后者可以压缩多个文件,但对于仅仅压缩一个文件的情况下,选择哪个更好呢??
请不吝赐教,谢谢!!
...全文
28 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
gzwrj 2002-05-24
  • 打赏
  • 举报
回复
import java.io.*;
import java.util.zip.*;

class Zip {
public static void main(String args[]) throws IOException {
byte b[] = new byte[512];
ZipOutputStream zout = new ZipOutputStream(System.out);
for(int i = 0; i < args.length; i ++) {
InputStream in = new FileInputStream(args[i]);
ZipEntry e = new ZipEntry(args[i].replace(File.separatorChar,'/'));
zout.putNextEntry(e);
int len=0;
while((len=in.read(b)) != -1) {
zout.write(b,0,len);
}
zout.closeEntry();
print(e);
}
zout.close();
}

public static void print(ZipEntry e){
PrintStream err = System.err;
err.print("added " + e.getName());
if (e.getMethod() == ZipEntry.DEFLATED) {
long size = e.getSize();
if (size > 0) {
long csize = e.getCompressedSize();
long ratio = ((size-csize)*100) / size;
err.println(" (deflated " + ratio + "%)");
}
else {
err.println(" (deflated 0%)");
}
}
else {
err.println(" (stored 0%)");
}
}
}
dasai 2002-05-24
  • 打赏
  • 举报
回复
FileOutputStream fos = new
FileOutputStream( zipFile );
CheckedOutputStream csum =
new CheckedOutputStream(
fos, new Adler32()
);
ZipOutputStream out =
new ZipOutputStream(
new BufferedOutputStream( csum )
);
BufferedReader in =
new BufferedReader(
new FileReader( srcfile )
);
ZipEntry entry = new ZipEntry( srcfile );
out.putNextEntry( entry );
int c = -1;
while( ( c = in.read() ) != -1 ) {
out.write( c );
}
in.close();
out.close();
其中,zipFile和srcfile为类似于"e:\x\xx\xxx\xxx.xx"这样的全路径
leonzhao 2002-05-24
  • 打赏
  • 举报
回复
把你的代码放上来,ZIP的,gz文件在PC上不流行
dasai 2002-05-24
  • 打赏
  • 举报
回复
我现在是想知道,在我用全路径构造zipentry的时候,能不能通过设置或是设么其他办法,让压缩时不包含这个全路径,只有文件
horseliu 2002-05-24
  • 打赏
  • 举报
回复
解开时,包含了压缩时提供的全路径,这是因为你在构造ZipEntry时用的是全路经。
压缩文件反而比原文件更大是不可能的。打开zip文件,一个文件的原始大小是ZipEntry.getSize();压缩后的大小是ZipEntry.getComproessedSize().

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧