/*
* 将下载下来的文件打成压缩包
* documentPath 原文件目录
* resultPath 结果文件名
*/
public String compression(String documentPath,String resultPath){
OutputStream outStream;
ZipOutputStream zos = null;
File file = new File(documentPath);
try {
outStream = new FileOutputStream(resultPath);
zos = new ZipOutputStream(outStream);// 将输入流获取的信息存储到zip的输出流里面
//读取目录中的所有文件
String[] list = file.list();
String[] filenames = new String[list.length];
for (int i = 0; i < list.length; i++) {
if ("".equals(list[i]))
continue;
filenames[i] = resultPath + list[i];
}
// 定义 数组大小
// int bufferSize = 1024 * 10 * 10;
byte[] b = new byte[102400];
int len = 0;
for (int i = 0; i < filenames.length; i++) {
File tFile = new File(filenames[i]);
if (!tFile.exists())
continue;
String shortName = tFile.getName();
zos.putNextEntry(new ZipEntry(shortName));
FileInputStream inStream = new FileInputStream(filenames[i]);
BufferedInputStream BuffedInStream = new BufferedInputStream(inStream);
while ((len = BuffedInStream.read(b)) != -1) {
zos.write(b, 0, len);
}
zos.flush();
inStream.close();
BuffedInStream.close();
}
deleteCatalogAndFiles(documentPath);//删除目录
}catch(Exception e) {
logger.error("压缩文件时出错", e);
}finally {
try {
zos.close();
} catch (IOException e) {
logger.error("关闭流出错", e);
}
}
return resultPath;
}
/*
* 删除文件目录下的文件及目录
*/
public void deleteCatalogAndFiles(String documentPath){
File file = new File(documentPath);
if (file.isDirectory()){
String[] children = file.list();//文件夹目录列表
for (String child : children)
{
deleteCatalogAndFiles(documentPath+ "//" + child);
}
}
file.delete();
}
读取目录下的文件将文件压缩
最新推荐文章于 2022-04-11 22:13:30 发布