java实现zip文件的解压

使用到的包 org.apache.commons

下载文件

url:文件所在地址需要是http://

filePath:将下载的文件保存的路径

public static void getDownloadResource(String url, String filePath) throws IOException {

		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
		OutputStream out = new FileOutputStream(file);
		downLoadByJdk(url, out);
	}


public static void downLoadByJdk(String url, OutputStream out) {
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			IOUtils.copy(conn.getInputStream(), out);
			out.close();
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!" + e);
			e.printStackTrace();
		}
	}

  

解压文件

/**
	 * 2 zip解压 3
	 * 
	 * @param srcFile
	 *            zip源文件 4
	 * @param destDirPath
	 *            解压后的目标文件夹 5
	 * @throws RuntimeException
	 *             解压失败会抛出运行时异常 6
	 */

	public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
		// 判断源文件是否存在
		if (!srcFile.exists()) {
			throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
		}
		// 开始解压
		ZipFile zipFile = null;
		try {
			zipFile = new ZipFile(srcFile,Charset.forName("GBK"));
			Enumeration<?> entries = zipFile.entries();
			while (entries.hasMoreElements()) {
				ZipEntry entry = (ZipEntry) entries.nextElement();
				// 如果是文件夹,就创建个文件夹
				if (entry.isDirectory()) {
					String dirPath = destDirPath + "/" + entry.getName();
					File dir = new File(dirPath);
					dir.mkdirs();
				} else {
					// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
					File targetFile = new File(destDirPath + "/" + entry.getName());
					// 保证这个文件的父文件夹必须要存在
					if (!targetFile.getParentFile().exists()) {
						targetFile.getParentFile().mkdirs();
					}
					targetFile.createNewFile();
					// 将压缩文件内容写入到这个文件中
					InputStream is = zipFile.getInputStream(entry);
					FileOutputStream fos = new FileOutputStream(targetFile);
					int len;
					int BUFFER_SIZE = 1024;
					byte[] buf = new byte[BUFFER_SIZE];
					while ((len = is.read(buf)) != -1) {
						fos.write(buf, 0, len);
					}
					// 关流顺序,先打开的后关闭
					fos.close();
					is.close();
				}
			}
		} catch (Exception e) {

			throw new RuntimeException("unzip error from ZipUtils", e);

		} finally {

			if (zipFile != null) {

				try {

					zipFile.close();

				} catch (IOException e) {

					e.printStackTrace();

				}

			}

		}

	}

  

猜你喜欢

转载自www.cnblogs.com/wangjinyu/p/10803577.html