java操作压缩包的完整代码

    技术2022-06-26  100

    ==========下面是java操作压缩包的完整代码==========

    package 压缩包测试;

    import java.io.File; import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.zip.*;import java.util.*;//import dianda.cwmanage.*;//import dianda.com.util.Format;/* * @author 何桂坤-2010-9-4号 * org.apache.tools.zip.*, * 能够解决不支持中文文件目录的问题,同时, * Ant的获得途径也比较多,一般的应用服务器中有这个包 * ,实在不行去下载个tomcat5.X,里面也有ant.jar,本人经过测试,可以使用。 */public class CompressBook { public CompressBook() {}String name="";public void zip(String inputFileName) throws Exception {//传入文件名 File filename=new File(inputFileName);//实例化文件 name=filename.getName();//得到完整文件名 String newnameString=filename.getName().substring(0,filename.getName().indexOf('.'));//截取有用的文件名 String zipFileName="f://IO流测试/"+newnameString+".zip";//设置打包后文件名字 System.out.println("将被打包的文件:"+zipFileName);//输出要打包的文件名 zip(zipFileName, filename);//参数1 参数2根据名子实例化一个文件}

    private void zip(String zipFileName, File inputFile) throws Exception {// ZipOutputStream以 ZIP 文件格式写入文件实现输出流过滤器。包括对已压缩和未压缩条目的支持。ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));//参数1{ZipOutputStream流}  参数2{被打包的文件File} 参数3 {压缩包里面被打包的文件的新名}File file=new File(zipFileName);String newnameString=file.getName().substring(0,file.getName().indexOf('.'));//截取有用的文件名System.out.println(newnameString);zip(out, inputFile, name);out.close();//关闭流}

    private void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory())// 测试此抽象路径名表示的文件是否是一个目录  {  File[] fl = f.listFiles();   out.putNextEntry(new ZipEntry(base + "/")); } else {       out.putNextEntry(new ZipEntry(base));    FileInputStream in = new FileInputStream(f);    int b;    System.out.println("===打包以后里面的文件名===:"+base);      while ( (b = in.read()) != -1) {     out.write(b);//把里面的内容读出来从新写入新文件  }  in.close();    }}public static void main(String[] args) { CompressBook compressBook=new CompressBook(); try {  compressBook.zip("f://IO流测试/2010-09-04生日小写.txt");   compressBook.zip("f://IO流测试/IO.html");  } catch (Exception e) {  // TODO Auto-generated catch block  e.printStackTrace(); }  /*唯一遗憾,美中不足的是,无论,  * java.util.zip或者org.apache.tools.zip  * 都不能解压rar工具打成的rar包,  * 搜了半天也找不到采用java解压rar工具打成的包,  * 盼望哪位高人能够提供解压rar工具打成的包,  */          //代码来自heguikun个人网站}}


    最新回复(0)