zip中添加文件夹


ZipEntry zipEntry = new ZipEntry(folder.substring(folder.lastIndexOf("\\")+1)+"\\"+filename + hz.substring(hz.lastIndexOf(".")));
//zip中添加文件夹,直接new ZipEntry("年度重大项目申请书\test.doc")
public boolean FoldersToZip(ArrayList<java.io.File> sourceFiles, String zipFilePath, String fileName, ArrayList<String> sourceFilesname) {
		boolean flag = false;
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		if (sourceFiles == null || sourceFiles.size() == 0) {
			Global.getInstance().LogApp("FoldersToZip-待压缩的文件不存在。");
		} else {
			try {
				java.io.File zipFile = new java.io.File(zipFilePath + "/" + fileName);
				if (zipFile.exists()) {
				} else {
					fos = new FileOutputStream(zipFile);
					if(fos!=null){	
					CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32());
					if(cos!=null){
					zos = new ZipOutputStream(cos);
					if(zos!=null){
					 zos.setEncoding("UTF-8");
					byte[] bufs = new byte[1024 * 10];
					for (int i = 0; i < sourceFiles.size(); i++) {
						// 创建ZIP实体,并添加进压缩包
						String hz = sourceFiles.get(i).getName();
						String folder=sourceFiles.get(i).getParent();
						String filename=sourceFilesname.get(i);
						ZipEntry zipEntry = new ZipEntry(folder.substring(folder.lastIndexOf("\\")+1)+"\\"+filename + hz.substring(hz.lastIndexOf(".")));
						if(zipEntry!=null){
						zipEntry.setUnixMode(755);
						zos.putNextEntry(zipEntry);
						/*zos.putNextEntry(new ZipEntry("1/"));会在压缩文件中建立名字为1的文件夹,zos.putNextEntry(new ZipEntry("1/description.xml"));会在压缩文件中建立名字为1的文件夹中建立description.xml文件*/
						// 读取待压缩的文件并写进压缩包里						
						if(sourceFiles.get(i).exists()){
							fis = new FileInputStream(sourceFiles.get(i));
							if(fis!=null){
							bis = new BufferedInputStream(fis, 1024 * 10);
							int read = 0;
							while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
								zos.write(bufs, 0, read);
								}
							  }
						}
						
						}
					}
					flag = true;
						}
					}
				}
			 }
			} catch (FileNotFoundException e) {
				Global.getInstance().LogError(e);
				e.printStackTrace();
				throw new RuntimeException(e); 
			} catch (IOException e) {
				Global.getInstance().LogError(e);
				e.printStackTrace();
				throw new RuntimeException(e);
			} finally {
				// 关闭流
				try {
					if (null != bis)
						bis.close();
					if (null != zos)
						zos.close();
				} catch (IOException e) {
					Global.getInstance().LogError(e);
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}
		return flag;
	}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值