java不解压直接读取压缩包中文件

文章目录

前言

最近写了个上传压缩包,将压缩包中的图片保存的接口,所以翻了翻网上文件流操作的博客,总结了一个不用解压,直接读取文件的方法

步骤

src=http___5b0988e595225.cdn.sohucs.com_images_20171005_bdc8cc9f754548a7aa835fb8ebe49df5.gif&refer=http___5b0988e595225.cdn.sohucs.gif

上代码

@RequestMapping(value = "packageUpload")
	public void packageUpload(HttpServletRequest request,
				HttpServletResponse response) {
		File file = null;
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile("file");

			if (null == multipartFile){
				return;
			}
			String originalFilename = multipartFile.getOriginalFilename();

			//判断上传文件必须是zip或者是rar否则不允许上传
			String[] filename = originalFilename.split("\\.");
			if (!filename[1].equals("zip") && !filename[1].equals("rar")){
				return;
			}

			//创建临时文件时,名称长度必须大于2
			file = File.createTempFile(filename[0].length() <= 2 ? "压缩包" + filename[0] : filename[0], filename[1]);
			multipartFile.transferTo(file);
			file.deleteOnExit();
			ZipFile zf = new ZipFile(file);
			Enumeration<?> zipEnum = zf.entries();
			ZipEntry ze;
			while (zipEnum.hasMoreElements()) {
				ze = (ZipEntry) zipEnum.nextElement();
				if (!ze.isDirectory()) {
					long size = ze.getSize();
					if (size > 0) {
						String[] name = ze.getName().split("\\.");
						String emojiName = name[0];
						String type = name[1];

						if (type.equals("jpg") || type.equals("png") || type.equals("gif") || type.equals("jpeg")){
							String[] split = emojiName.split("/");
							String picName = split[1] + "." + type;
		
							InputStream is = zf.getInputStream(ze);
							logger.info("picName:" + picName + ",size:" + size + ",inputStream:" + is);
							///到这里调用上传文件的方法上传这个图片就可以了
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("packageUpload_error:" , e);
		}
	}
	
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享