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"这样的全路径
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%)"); } } }
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"这样的全路径
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%)");
}
}
}
压缩文件反而比原文件更大是不可能的。打开zip文件,一个文件的原始大小是ZipEntry.getSize();压缩后的大小是ZipEntry.getComproessedSize().