JAVA 压缩文件和解压文件

来源:互联网 发布:pc护眼软件 编辑:程序博客网 时间:2024/05/22 17:45

JAVA 压缩文件和解压文件

使用到Apache的一个开源Jar包ant-1.9.4.jar

Java 压缩文件

    public  void zip(List<File> files, String zipFilepath) throws BuildException, RuntimeExceptioan {          Zip zip = new Zip();        for (File file : files) {             Project proj = new Project();               FileSet fileSet = new FileSet();               fileSet.setProject(proj);             fileSet.setFile(file);  //这里是将给定的file压缩起来,也可以将给定的dir压缩起来,需要使用fileSet.setDir()             zip.setProject(proj);               zip.addFileset(fileSet);        }        zip.setDestFile(new File(zipFilepath));          zip.setEncoding("utf-8");          zip.execute();      } 

压缩文件就是这样,可以将给定的文件压缩起来,也可以将给定的dir压缩起来。

Java解压文件

public static void unZipFiles(File zipFile){        String unZipPath = zipFile.getParentFile().getPath() + "/" + zipFile.getName().substring(0, zipFile.getName().lastIndexOf("."));        try {            ZipFile zf = new ZipFile(zipFile);            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile));            ZipEntry zipEntry = null;            while((zipEntry = zipInputStream.getNextEntry()) != null){                String fileName = zipEntry.getName();                File temp = new File(unZipPath + "/" + fileName);                System.out.println(temp.getPath());                if (!temp.getParentFile().exists()) {                    temp.getParentFile().mkdirs();                }                OutputStream os = new FileOutputStream(temp);                InputStream is = zf.getInputStream(zipEntry);                int len = 0;                while((len = is.read()) != -1){                    os.write(len);                }                os.close();                is.close();            }            zipInputStream.close();        } catch (ZipException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }

这个就是解压文件。
仅供自己参考

0 0
原创粉丝点击