解压ZIP文件

/**
 * 解压zip文件
 * @param inputFile
 * @param outputFile
 */
private void unZip(File inputFile, File outputFile) {
	if (!outputFile.exists()) {
		outputFile.mkdirs();
	}else {
		delDir(outputFile);
		outputFile.mkdirs();
	}
	ZipFile zipFile = null;
	ZipInputStream zipInput = null;
	ZipEntry entry = null;
	OutputStream output = null;
	InputStream input = null;
	File file = null;
	try {
		zipFile = new ZipFile(inputFile);
		zipInput = new ZipInputStream(new FileInputStream(inputFile));
		String path = outputFile.getAbsolutePath() + File.separator;
		while ((entry = zipInput.getNextEntry()) != null) {
			input = zipFile.getInputStream(entry);
			if(entry.getName().lastIndexOf("/") == entry.getName().length() - 1 || entry.getName().lastIndexOf("\\") == entry.getName().length() - 1) {
				continue;
			}
			String fileName = (path + entry.getName()).replace("/", File.separator).replace("\\", File.separator);

			file = new File(fileName.substring(0, fileName.lastIndexOf(File.separator)));
			file.mkdirs();

			output = new FileOutputStream(fileName);

			write(input, output);
			output.close();
		}
	} catch (ZipException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			if (output != null) {
				output.close();
			}

			if (zipInput != null) {
				zipInput.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

/**
 * 输出解压的文件
 * @param input
 * @param output
 */
private void write(InputStream input, OutputStream output) {
	int len = -1;
	byte[] buff = new byte[1024];
	try {
		while ((len = input.read(buff)) != -1) {
			output.write(buff, 0, len);
		}
		output.flush();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

/**
 * 删除文件夹
 * @param file
 */
private void delDir(File file){
	if (file.isDirectory()) {
		String[] children = file.list();
		for (int i=0; i<children.length; i++) {
			delDir(new File(file, children[i]));
		}
	}
	file.delete();
}

猜你喜欢

转载自www.cnblogs.com/diehuacanmeng/p/13402190.html