`

java压缩/解压缩文件

阅读更多
忘了转载谁的了,对原作者表身敬意!

org.apache.tools.zip.ZipEntry以及org.apache.tools.zip.ZipOutputStream

/**
	 * 压缩文件
	 * 
	 * @param file
	 * @param out
	 * @param base
	 * @throws IOException
	 */
	public static synchronized void myzip(File file, ZipOutputStream out, String base) throws IOException {
		if (file.isDirectory()) {
			out.putNextEntry(new ZipEntry(base + "/"));
			File[] files = file.listFiles();
			for (File f : files) {
				myzip(f, out, base + "/" + f.getName());//递归
			}
		} else {
			if (StringUtils.isBlank(base)) {
				base = file.getName();
			}
			out.putNextEntry(new ZipEntry(base));
			int length;
			byte[] buff = new byte[1024];
			FileInputStream in = null;
			try {
				in = new FileInputStream(file);
				while ((length = in.read(buff)) != -1) {
					out.write(buff, 0, length);//生成压缩file
				}
			} finally {
				in.close();
			}
		}
	}

	/**
	 * 解压缩文件
	 * 
	 * @param zipFilename
	 * @param outputDirectory
	 * @throws IOException
	 */
	public synchronized void unzip(String zipFilename, String outputDirectory) throws IOException {
		File outFile = new File(outputDirectory);
		if (!outFile.exists()) {
			outFile.mkdirs();
		}
		ZipFile zipFile = new ZipFile(zipFilename);
		Enumeration en = zipFile.getEntries();
		ZipEntry zipEntry = null;
		while (en.hasMoreElements()) {
			zipEntry = (ZipEntry) en.nextElement();
			File f = new File(outFile.getPath() + File.separator + zipEntry.getName());
			if (zipEntry.isDirectory()) {
				f.mkdirs();//创建路径
			} else {
				if (!f.getParentFile().exists()) {
					f.getParentFile().mkdirs();
				}
				//if (!f.exists()) {
				//	f.createNewFile();
				//}
				InputStream in = zipFile.getInputStream(zipEntry);
				FileOutputStream out = new FileOutputStream(f);//创建文件
				try {
					int length;
					byte[] buff = new byte[BUFFEREDSIZE];
					while ((length = in.read(buff)) != -1) {
						out.write(buff, 0, length);//读取流
					}
					// out.flush();    
				} catch (IOException e) {
					throw e;
				} finally {
					out.close();
					in.close();
				}
			}
		}
	}

//网页下载
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(s, "utf-8"));

response.getOutputStream();
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics