Java实现压缩一个目录下所有图片文件
import java.io.*;
import java.util.*;
import java.util.zip.*;
/**
* 打包照片文件
*/
public class PhotoZip
{
public static void main(String[] args)
{
if (args.length < 2)
{
System.out.println("Usage: java PhotoZip photodir target.zip");
}
else
{
try
{
byte[] buf = new byte[1024]; // 缓冲区
File dir = new File(args[0]); // 照片目录
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(args[1])); // 压缩包流
String[] files = dir.list(); //列表照片目录下文件
String fPath = dir.getCanonicalPath();
if (!fPath.endsWith(File.separator))
{
fPath = fPath + File.separator;
}
for(int idx = 0; idx < files.length; idx ++)
{
if (files[idx].length() >= 12)
{
try
{
zos.putNextEntry(new ZipEntry(files[idx].substring(0, 8) + ".jpg")); // 统一文件名为8位+扩展名.jpg
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fPath + files[idx]));
while (bis.read(buf, 0, 1024) != -1)
{
zos.write(buf);
}
bis.close();
zos.closeEntry();
}
catch (ZipException zexp)
{
zexp.printStackTrace();
}
}
}
zos.close();
}
catch (Exception exp)
{
exp.printStackTrace();
}
}
}
};



浙公网安备 33010602011771号