- package tests;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipOutputStream;
- public class ZipUtil {
- private static File zip;
- private static ZipOutputStream zipOut;
- private InputStream input;
- public ZipUtil(){
- try {
- zipOut = new ZipOutputStream(new FileOutputStream(zip));
- zipOut.setComment("hello2");
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- public void zipFile(File file) {
- if (file.isDirectory()) {
- File[] files = file.listFiles();
- for (int i = 0; i < files.length; i++) {
- if (files[i].isDirectory()) {
- zipFile(files[i]);
- } else {
- try {
- input = new FileInputStream(files[i]);
- zipOut.putNextEntry(new ZipEntry(file.getName()
- + File.separator + files[i].getName()));
- int temp = 0;
- while ((temp = input.read()) != -1) {
- zipOut.write(temp);
- }
- input.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- try {
- zipOut.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else {
- try {
- input = new FileInputStream(file);
- zipOut.putNextEntry(new ZipEntry(file.getName()));
- int temp = 0;
- while ((temp = input.read()) != -1) {
- zipOut.write(temp);
- }
- input.close();
- zipOut.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- zip = new File("d:" + File.separator + "hello.rar");
- File file = new File("d:" + File.separator + "hello");
- new ZipUtil().zipFile(file);
- }
- }
java压缩文件工具类
最新推荐文章于 2024-08-20 17:23:57 发布