打包

向压缩包里添加文件时直接把服务器上的文件用流读进来就行,不用非把文件放到同一个目录,用程序生成压缩包和用命令行工具是不一样的,不要想当然。 写了个示例程序,你可以参考一下。这个示例不使用临时文件,把 OutputStream os替换成你下载用的输出流就可以实现一边压缩一边下载。注意java.util.zip不支持非ascii文件名。想支持中文文件名可以用apache ant或其他的库。

import java.io.*;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class ZipTest {

public static void main( String[] args ) {

try {

writeZip();

} catch ( IOException e ) {

e.printStackTrace();

}

}

private static void writeZip() throws IOException {

String[] files = { "/ws/dir1/file1", "/ws/dir2/file2", "/ws/file3", "/pub/success.wav" };

OutputStream os = new BufferedOutputStream( new FileOutputStream( "/ws/archive.zip" ) );

ZipOutputStream zos = new ZipOutputStream( os );

byte[] buf = new byte[8192];

int len;

for ( String filename : files ) {

File file = new File( filename );

if ( !file.isFile() ) continue;

ZipEntry ze = new ZipEntry( file.getName() );

zos.putNextEntry( ze );

BufferedInputStream bis = new BufferedInputStream( new FileInputStream( file ) );

while ( ( len = bis.read( buf ) ) > 0 ) {

zos.write( buf, 0, len );

}

zos.closeEntry();

}

zos.close();

}

}