可以将某个文件进行压缩打包为zip文件,直接上代码
有对单个文件进行压缩,也有对某个文件夹进行压缩
public class ZipFileTool
{
public static int BUFFER_SIZE_2048 = 2048;
public static String ZIP_SUFFIX = ".zip";
/**
* 压缩单个文件
*
* @param filePath D:\xxx\xxx\ 生成路径
* @throws IOException
*/
public static void zipSingleFile(String filePath) throws IOException
{
byte[] bytes = new byte[BUFFER_SIZE_2048];
String folder = filePath.substring(0, filePath.lastIndexOf("."));
// 获取文件名
String fileName = new File(filePath).getName();
// 生成的zip绝对路径
String absPath = folder + ZIP_SUFFIX;
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(absPath)));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
zos.putNextEntry(new ZipEntry(fileName)); // 这里的fileName是在生成在压缩包的文件名
int len = 0;
while ((len = bis.read(bytes, 0, BUFFER_SIZE_2048)) != -1)
{
zos.write(bytes, 0, len);
}
zos.close();
bis.close();
}
/**
* 压缩某个文件夹
*
* @param zipFileName 文件绝对路径 D:\xxx\xxx\x.zip
* @param filePath D:\xxx\xxx\ 生成路径
* @throws IOException
*/
public static void zipFilesInPath(final String zipFileName, final String filePath) throws IOException
{
final FileOutputStream dest = new FileOutputStream(zipFileName); // 创建了sb.zip
final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
try
{
process(filePath, out, "", zipFileName);
}
finally
{
try
{
out.close();
dest.close();
}
catch (IOException io)
{
}
}
}
private static void process(final String filePath,
final ZipOutputStream out,
final String fileFolder,
final String zipFileName) throws IOException
{
byte[] data = new byte[BUFFER_SIZE_2048];
final File folder = new File(filePath);
List<String> files = new ArrayList<String>();
if (null != folder)
{
String[] fs = folder.list();
if (fs != null)
{
files = Arrays.asList(fs);
}
}
for (String file : files)
{
if (!zipFileName.contains(file)) // 由于这个file可能是由fileOutputStream构建出的压缩文件
{
File subFile = new File(filePath + file);
if (subFile.isDirectory()) // 递归调用,进入下一级目录
{
String destFolder = file;
if (!"".equals(fileFolder))
{
destFolder = fileFolder + File.separator + file;
}
process(filePath + file + File.separator, out, destFolder, zipFileName);
}
else
{
final FileInputStream fi = new FileInputStream(filePath + file);
final BufferedInputStream origin = new BufferedInputStream(fi, BUFFER_SIZE_2048);
try
{
String destFolder = file;
if (!"".equals(fileFolder))
{
destFolder = fileFolder + File.separator + file;
}
out.putNextEntry(new ZipEntry(destFolder)); // zipoutputstream
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE_2048)) != -1)
{
out.write(data, 0, count);
}
}
finally
{
try
{
origin.close();
fi.close();
}
catch (IOException io)
{
}
}
}
}
}
}
}