ITeye博客

java zip压缩文件中文乱码

wingware · 2012-12-27 19:39 · 编程语言 · Markdown

1.解压文件

 public static Map<String,File> unzip(File zipFile) throws IOException {
		Map<String,File> map = new Hashtable<String,File>();
		org.apache.tools.zip.ZipFile zfile = new org.apache.tools.zip.ZipFile(zipFile,"GBK");
		Enumeration<?> enumeration = zfile.getEntries();
		InputStream is = null;
		while (enumeration.hasMoreElements()) {
			ZipEntry entry = (ZipEntry) enumeration.nextElement();
			if (!entry.isDirectory()) {
				is = zfile.getInputStream(entry);
				BufferedInputStream bis = new BufferedInputStream(is);
				File temp = new File(Constant.FTP_LOCAL_DIR+""+CommonUtils.getToday()+"_upload/"+entry.getName());
				if(!temp.getParentFile().exists()){
					temp.getParentFile().mkdirs();
				}
				OutputStream bos = new FileOutputStream(temp);
				IOUtils.copy(bis, bos);
				bis.close();
				bos.close();
				is.close();
				map.put(entry.getName(), temp);
			}
		}
		return map;
	}

2.压缩文件

private static File zip(List<File> fileList,String zipFileName) throws Exception{
		File zipFile=null;
		if (fileList.size() > 0) {
			zipFile = new File(zipFileName);
			FileOutputStream fos = new FileOutputStream(zipFile);
			ZipOutputStream zos = new ZipOutputStream(fos);
			for (File f : fileList) {
				ZipEntry entry = new ZipEntry(f.getName());
				zos.setEncoding("gbk");
				zos.putNextEntry(entry);
				CommonUtils.addFile(f, zos);
			}
			zos.close();
			fos.close();
		}
		return zipFile;
	}
	public static void addFile(File file, OutputStream zos) throws IOException {
		InputStream in = new FileInputStream(file);
		byte[] b = new byte[1024000];
		int length;
		while ((length = in.read(b)) > -1) {
			zos.write(b, 0, length);
			zos.flush();
		}
		in.close();
	}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。