zip文件解压并增加到桌面

zip文件解压

/**
	 * 解压zip
	 *
	 * @param zipFile
	 * @param descDir
	 * @throws Exception
	 */
	@RequestMapping("/ff")
	@ResponseBody
	public  AjaxResult unZipFiles(MultipartFile fil, String descDir) throws Exception {
		System.out.println("******************解压开始********************");
		  File zipFile = null;
		    if(fil.equals("") ||fil.getSize()<=0){
		    	fil = null;
		    }else {
		            InputStream ins = null;
		            ins = fil.getInputStream();
		            zipFile = new File(fil.getOriginalFilename());
		            inputStreamToFile(ins, zipFile);
		            ins.close();
		    }
		descDir = Global.getAvatarPath()+DateUtils.datePath() ;
		File pathFile = new File(descDir);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		@SuppressWarnings("resource")
		ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
		for (Enumeration<?> entries = zip.entries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir + "/" + zipEntryName).replaceAll("\\*", "/");
			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			OutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			if ((zipEntryName.trim().lastIndexOf("/")) == -1) {

			}
			in.close();
			out.close();
		}

		System.out.println("******************解压完毕********************");
		System.out.println("******************遍历文件夹********************");
		String parent_id = "";
		traverse(descDir, parent_id);
		return success();
	}
	
	
	public  void inputStreamToFile(InputStream ins, File file) {
	    try {
	        OutputStream os = new FileOutputStream(file);
	        int bytesRead = 0;
	        byte[] buffer = new byte[8192];
	        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
	            os.write(buffer, 0, bytesRead);
	        }
	        os.close();
	        ins.close();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	

	/**
	 * 文件夹遍历
	 * 
	 * @param path
	 * @throws Exception
	 */
	public  void traverse(String path, String parent_id) throws Exception {
		System.out.println("path---->" + path);
		File file = new File(path);
		if (file.exists()) {
			File[] files = file.listFiles();
			if (files.length == 0) {
				System.out.println("文件夹是空的!");
				return;
			} else {
				String k_id = "aaa";

				for (File file2 : files) {
					if (file2.isDirectory()) {// 文件夹

						traverse(file2.getAbsolutePath(), parent_id);
						parent_id = k_id;
					} else if (file2.isFile()) {// 文件
						if (file2.getName().endsWith(".xls")||file2.getName().endsWith(".xlsx")) {
							
							ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
							List<SysUser> userList = util.importExcel(new FileInputStream(file2));
							
							List<SysUser> users = new ArrayList<>();
							for (SysUser sysUser : userList) {
								if (sysUser.getRecordPicture()!=null) {
									sysUser.setRecordPicture(DateUtils.datePath()+"/"+sysUser.getRecordPicture());
									users.add(sysUser);
								}
							}
							String operName = ShiroUtils.getSysUser().getLoginName();
							userService.importUser(users, true, operName);
							FileUtils.deleteFile(file2.getCanonicalPath());
						}
					}
				}
			}
		} else {
			System.out.println("文件不存在!");
		}
	}
	

将目标文件压缩为zip文件下载到桌面

1.将文件及图片打包压缩文件zip文件

@RequestMapping("/download")
	@ResponseBody
	public  void download(HttpServletRequest request, HttpServletResponse response) throws Exception{
		  response.setCharacterEncoding("UTF-8");
	        //获得要下载的文件名
	        String fileName = "导入用户示例.xlsx";
	        String fileName2 = "张1.jpg";
	        String fileSaveRootPath = "D:\\Work\\fw\\profile\\avatar\\示例\\";
	        //得到要下载的文件
	        File file = new File(fileSaveRootPath, fileName);
	        File file2 = new File(fileSaveRootPath, fileName2);
	        System.out.println("Excel文件保存路径1:" + fileSaveRootPath + fileName);
	        System.out.println("Excel文件保存路径2:" + fileSaveRootPath + fileName2);
	        //如果文件不存在
	        if (!file.exists() ) {
	            request.setAttribute("message", "您要下载的资源已被删除!!");
	            request.getRequestDispatcher("/message.jsp").forward(request, response);
	            return ;
	        }
	        //先压缩
	        String zipName = "导入用户示例.zip";
	        //获取当前用户桌面
	        File desktopDir = FileSystemView.getFileSystemView() .getHomeDirectory();
	        String desktopPath = desktopDir.getAbsolutePath();
	        String zipPath = desktopPath+"\\" + zipName;
	        ZipOutputStream zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath)));
	        ZipEntry zEntry = new ZipEntry(file.getName());
	        zipOutput.putNextEntry(zEntry);
	        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
	        byte[] buffer = new byte[1024];
	        int read = 0;
	        while((read = bis.read(buffer)) != -1){
	            zipOutput.write(buffer, 0, read);
	        }
	        zEntry = new ZipEntry(file2.getName());
	        zipOutput.putNextEntry(zEntry);
	        bis = new BufferedInputStream(new FileInputStream(file2));
	        while((read = bis.read(buffer)) != -1){
	            zipOutput.write(buffer, 0, read);
	        }
	        bis.close();
	        zipOutput.close();
	        //创建输出流,下载zip
	        try(OutputStream out = response.getOutputStream();
	            FileInputStream in = new FileInputStream(new File(zipPath));){
	            //设置响应头,控制浏览器下载该文件
	            response.setHeader("Content-Type","application/octet-stream");
	            response.setHeader("Content-Disposition",
	                    "attachment;filename="+java.net.URLEncoder.encode(zipName, "UTF-8"));
	            while((read = in.read(buffer)) != -1){
	                out.write(buffer, 0, read);
	            }
	            System.out.println("zip下载路径:"+zipPath);
	        }finally {
	            try {
	                /*//删除压缩包
	                File zfile = new File(zipPath);
	                zfile.delete();*/
	            }catch (Exception e){
	                e.printStackTrace();
	            }
	        }
	}

2.将zip实例文件放到工程中通过浏览器直接下载

@RequestMapping("/download")
@ResponseBody
public  String download(HttpServletResponse response) throws Exception{
	  	response.setCharacterEncoding("UTF-8");
		String url = "http://localhost:8080/user.zip";
		Runtime runtime = Runtime.getRuntime();
			try {
				runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
			} catch (IOException e) {
				 return null;
			}
	 	return "";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值