java压缩文件及文件夹(包括空文件夹)

这里输入代码
```if(file.isDirectory()){
				File[] files = file.listFiles();
				if(files!=null&&files.length>0){
					for(File fileSec:files){
						recursionZip(zipOut, fileSec, baseDir + file.getName() + File.separator);
					}
				}else{
					zipOut.putNextEntry(new EncryptZipEntry(baseDir+file.getName()+"/"));
				}
			}else{
					byte[] buf = new byte[2048];
					InputStream input = new FileInputStream(file);
					zipOut.putNextEntry(new EncryptZipEntry(baseDir + file.getName()));
				    int len;
					while((len = input.read(buf)) != -1){
					    zipOut.write(buf, 0, len);
					}
					input.close();
				}```
这里输入代码

转载于:https://my.oschina.net/u/1054538/blog/727913

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,使用ZipOutputStream压缩文件夹时,文件夹不会被压缩。这是因为Zip文件格式本身不支持文件夹。 如果你希望在压缩文件夹时也包含文件夹,可以在压缩文件夹时手动添加一个文件夹ZipEntry。以下是修改后的示例代码: ```java import java.io.*; import java.util.zip.*; public class ZipFolder { public static void main(String[] args) throws Exception { // 指定要压缩的文件夹路径 String sourceFolder = "C:\\MyFolder"; // 指定压缩后的文件路径和名称 String zipFile = "C:\\MyFolder.zip"; FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); // 添加文件夹ZipEntry ZipEntry ze = new ZipEntry("EmptyFolder/"); zos.putNextEntry(ze); zos.closeEntry(); // 递归遍历文件夹,将文件夹内的每个文件添加到压缩文件中 addFolderToZip(sourceFolder, sourceFolder, zos); zos.close(); fos.close(); } private static void addFolderToZip(String folderPath, String basePath, ZipOutputStream zos) throws Exception { File folder = new File(folderPath); // 如果是文件夹,则递归遍历文件夹,将文件夹内的每个文件添加到压缩文件中 if (folder.isDirectory()) { String[] fileList = folder.list(); for (String fileName : fileList) { String filePath = folderPath + File.separator + fileName; addFolderToZip(filePath, basePath, zos); } } else { // 如果是文件,则将文件添加到压缩文件中 String relativePath = folderPath.substring(basePath.length() + 1); ZipEntry ze = new ZipEntry(relativePath); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream(folderPath); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } fis.close(); zos.closeEntry(); } } } ``` 在这个示例代码中,我们首先手动添加一个文件夹ZipEntry。然后,我们递归遍历文件夹,将文件夹内的每个文件添加到压缩文件中。如果遇到文件夹,则递归调用addFolderToZip方法。如果遇到文件,则将文件添加到压缩文件中。最后,我们关闭ZipOutputStream和FileOutputStream对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值