JAVA压缩文件夹包括里面的文件,可以设置压缩后的目录结构

本文提供了一个使用Java实现的文件夹压缩示例代码。通过该示例,读者可以了解到如何利用`ZipOutputStream`和`ZipEntry`来压缩指定文件夹下的所有文件,并将压缩后的文件保存到指定位置。此外,还介绍了如何处理文件路径和避免乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test.downloadzip;


/* 
 * 在进行压缩流操作时建议使用开源的类库org.apache.tools.zip.*, 
 * 不要用java.util.zip.*类库,这个在实现上没有前面那个做的完善。 
 */


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipDemo {


public static TreeSet<String> ts = new TreeSet<String>();


public static void main(String[] args) throws IOException {
// 需要压缩的目录
File sFolder = new File("D:\\leo\\file\\pic");

// 压缩之后的目录,如果是网络下载情况可以将流写入response就好了
File zipFolder = new File("d:\\zipDown\\test.zip");


ZipFolderMethod(sFolder, zipFolder);


System.out.println("导出成功");


}


public static void ZipFolderMethod(File sFoder, File zipFolder) throws IOException {
// TODO Auto-generated method stub


ZipOutputStream zipoutFolder = new ZipOutputStream(new FileOutputStream(zipFolder));


InputStream in = null;


// zipoutFolder.setEncoding("GBK"); //为解决注释乱码
zipoutFolder.setComment("文件夹的压缩");


// 列出所有文件的路径,保存到集合中,在ListAllDirectory(sFoder)方法中用到递归
TreeSet<String> pathTreeSet = ListAllDirectory(sFoder);


String[] pathStr = pathTreeSet.toString().substring(1, pathTreeSet.toString().length() - 1).split(",");


for (int i = 0; i < pathStr.length; i++) {
String filePath = pathStr[i].trim();
StringBuffer pathURL = new StringBuffer();
String[] tempStr = filePath.split("\\\\"); // 这个地方需要注意,在Java中需要“\\\\”表示“\”字符串。


// 这里的变量j是从第几层开始打压缩包
for (int j = 6; j < tempStr.length - 1; j++) {
pathURL.append(tempStr[j] + File.separator);
}
String path = pathURL.append(tempStr[tempStr.length - 1]).toString();


in = new FileInputStream(new File(filePath));


zipoutFolder.putNextEntry(new ZipEntry(path));


int temp = 0;
while ((temp = in.read()) != -1) {
zipoutFolder.write(temp);
}


in.close();
}
zipoutFolder.close();
}


public static TreeSet<String> ListAllDirectory(File sFolder) {
if (sFolder != null) {
if (sFolder.isDirectory()) {
File f[] = sFolder.listFiles();
if (f != null) {
for (int i = 0; i < f.length; i++) {
ListAllDirectory(f[i]);
}
}
} else {
ts.add(sFolder.toString());
}
}
return ts;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值