java 将文件/目录下 zip压缩文件解压并删除压缩包

package filetest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipException;

import javax.swing.JFileChooser;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

public class FileOperation {

	private JFileChooser fChooser;

	/**
	 * 选择目录或文件
	 * 
	 * @return
	 */
	public File getChooseFile() {
		fChooser = new JFileChooser("F:\\资料文档\\视频资料\\黑马程序员\\Java基础视频");//默认路径
		fChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);// 可选文件和目录
		fChooser.setDialogTitle("Please choose a dictionary or a file~");
		int result = fChooser.showOpenDialog(fChooser);
		if (JFileChooser.APPROVE_OPTION == result) {// “确定”
			return fChooser.getSelectedFile();
		}
		return null;
	}

	public static void main(String[] args) {
		FileOperation fo = new FileOperation();
		File file = fo.getChooseFile();
		if (file != null)
			fo.unZipFile(file);
		System.exit(0);
	}

	/**
	 * 解压目录/文件
	 * 
	 * @param file
	 * @throws IOException
	 * @throws ZipException
	 */
	public void unZipFile(File file) {
		if (file.isDirectory()) {// 目录
			File[] files = file.listFiles();
			for (File tempFile : files) {
				unZipFile(tempFile);
			}
		} else {// 文件
			try {
				if (!file.getName().endsWith(".zip"))
					return;
				ZipFile zipFile = new ZipFile(file.getPath(), "GBK");
				Enumeration entries = zipFile.getEntries();
				String path = file.getParent(); // 获取相对路径
				while (entries.hasMoreElements()) {
					ZipEntry zipEntry = (ZipEntry) entries.nextElement();
					String fileName = zipEntry.getName();
					File newFile = new File(path + "/" + fileName);
					createFile(newFile, zipFile, zipEntry);
				}
				zipFile.close();//关闭压缩文件,否则不能删除压缩包
				file.delete();//删除压缩包
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 解压压缩包里每个文件
	 * @param file
	 * @param zipFile
	 * @param zipEntry
	 */
	public void createFile(File file, ZipFile zipFile, ZipEntry zipEntry) {
		if (file.isDirectory()) {
			if (!file.exists()) {
				file.mkdir();
			}
		} else {
			try {
				InputStream is = null;
				OutputStream os = null;
				is = zipFile.getInputStream(zipEntry);
				os = new FileOutputStream(file);
				byte[] bytes = new byte[1024];
				int len = 0;
				while ((len = is.read(bytes, 0, bytes.length)) != -1) {
					os.write(bytes, 0, len);
				}
				is.close();
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

你可能感兴趣的:(JAVA)