<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    posts - 1,  comments - 25,  trackbacks - 0

    如果已存在以壓縮文件a.jar,現在想把一個a.class文件或com/my/b.calss包含文件夾的文件添加到壓縮包中;

    1.創建臨時文件

    2..先解壓目標壓縮Jar文件 到臨時文件夾

    3.拷貝源文件到臨時文件夾

    4.再壓縮臨時文件夾

    5.再刪除臨時文件夾

    方法可能有些笨,但是我找了好久也沒找到現成API實現這個功能。所以和大家分享,共寫了三個類

    第一個類:

    package com.jar;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    /**
    * 文件夾或文件拷貝到指定目錄
    * 文件夾的刪除
    * @author zhang
    *
    */
    public class FolderCopy {

    /**
    * 測試主程序
    */
    public static void main(String args[]) throws IOException {
       String url1 = "D:/wtk/SonyEricsson/JavaME_SDK_CLDC/README.html";
       String url2 = "c:/temp/";
       copyDirectiory(url1, url2);
    }
    /**
    * 文件夾拷貝,將源文件夾下的所有文件及其子文件夾(文件)拷貝到目標文件夾(文件)下

    * @param sourceFile
    *            源文件夾或文件
    * @param desFile
    *            目標文件夾
    * @return
    */
    public static boolean copyDirectiory(String sourceFile, String desFile)
        throws IOException {
       File des = new File(desFile);
       if (!des.exists())
        des.mkdirs();// 不存在目標文件夾就創建
      
       File source = new File(sourceFile);
       if (!source.exists()) {
        System.out.println(source.getAbsolutePath()
          + "========源文件不存在!=======");
        return false;
       }
       FileInputStream input = null;
       FileOutputStream output = null;

       try {
        if (source.isFile()) { // 如果是文件 則讀源文件 寫入目標文件
         input = new FileInputStream(source);
         File f = new File(desFile + "/"
           + source.getName());
         output = new FileOutputStream(f);
         byte[] b = new byte[1024 * 5];
         int len;
         while ((len = input.read(b)) != -1) { // 讀文件
          output.write(b, 0, len); // 向目標文件寫文件
         }
         input.close();
         output.flush();
         output.close();
        } else if (source.isDirectory()) { // 如果是文件夾 遞歸讀取子文件或文件夾
        
         File[] file = source.listFiles();
         for (int i = 0; i < file.length; i++) {
          if(file[i].isDirectory())
           copyDirectiory(sourceFile + "/" + file[i].getName(),
            desFile + "/" + file[i].getName());
          else{
           copyDirectiory(sourceFile + "/" + file[i].getName(),
             desFile + "/");
          }
         }
        
        }
        return true;
       } catch (Exception e) {
        e.printStackTrace();
        return false;
       } finally {
        if (input != null)
         input.close();
        if (output != null)
         output.close();
       }
    }
    /**
    * 刪除文件或文件夾
    * @param file
    */
    public static void deleteFile(File file){ 
         if (file.exists()){ 
          if(file.isFile()){ 
           file.delete(); 
          }else if(file.isDirectory()){ 
           File files[] = file.listFiles(); 
           for(int i=0;i<files.length;i++){ 
            deleteFile(files[i]); 
           } 
          } 
          file.delete(); 
         }else{ 
          System.out.println("所刪除的文件不存在!"+'\n'); 
         } 
       }


    }

    第二個類BatchJar :

    package com.jar;

    import java.io.File;
    /**
    * 批處理:在指定文件夾中的所有Jar文件中添加文件或文件夾
    * @author zhang
    *
    */

    public class BatchJar {

    /**
    * @param args
    */
    public static void main(String[] args) {
       // TODO Auto-generated method stub
       BatchJar jar = new BatchJar();
       jar.batchJar("D:/temp/瘋狂農場", "jar", "D:/temp/ashinanren.jar");
    }
    public void batchJar(String dir, String fileType, String fileName){
       System.out.println(fileName+" 即將被添加到"+dir+"中的"+fileType+"文件中..");
       batchRar(dir,fileType,fileName);
       System.out.println("添加完成!");
    }
    /**

    * @param dir
    *            需要遍歷的文件夾
    * @param fileType
    *            壓縮文件類型 rar jar zip
    * @param fileName
    *            要添加的文件或文件夾

    *            遍歷文件夾 拼寫批處理命令
    */
    JARDemo jar = new JARDemo();
    public void batchRar(String dir, String fileType, String fileName) {

       File file = new File(dir);
       if (file.exists()) {
        if (file.isFile()) { //
         if (isType(file, fileType)) {
          
          jar.fileAddToJar(fileName, file.getAbsolutePath());    
         }

        } else if (file.isDirectory()) {
         File files[] = file.listFiles();
         for (int i = 0; i < files.length; i++) {
          batchRar(files[i].getAbsolutePath(), fileType, fileName);
         }
        }
        // file.delete();
       } else {
        System.out.println("所刪除的文件不存在!" + '\n');
       }
      

    }
    /**
    * 判斷是否為指定文件類型
    */
    private boolean isType(File file, String fileType) {
       if (file == null) {
        return false;
       }
       String fileName = file.getAbsolutePath();
       String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);// 后綴
       // System.out.println("====后綴:"+suffix);
       if (fileType.equals(suffix)) {
        return true;
       }
       return false;
    }
    }

    第三個類JARDemo :
    package com.jar;

    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.Enumeration;
    import java.util.jar.JarEntry;
    import java.util.jar.JarFile;
    import java.util.jar.JarOutputStream;

    /**
    * 壓縮指定文件夾
    * 解壓指定壓縮文件
    * 把指定源文件或文件夾添加到指定壓縮包中
    * @author zhang
    *
    */

    public class JARDemo {
    public static void main(String[] args) {
       JARDemo t = new JARDemo();

       t.fileAddToJar("d:/com", "d:/temp/shinanren.jar");
    }

    /**
    * 把指定源文件添加到指定壓縮包中

    * @param sourceFileName
    *            要壓縮到指定目標壓縮文件的源文件或文件夾
    * @param destFileName
    *            目標壓縮文件
    * @throws IOException
    */
    public void fileAddToJar(String sourceFileName, String jarName) {
    //   System.out.println("**=="+sourceFileName);
       // 先解壓到臨時文件夾,存在先刪除 不存在直接創建
       String tempFileName = "c:/temp";
       File tempDir = new File(tempFileName);
       try {

        if (tempDir.exists()) {
         FolderCopy.deleteFile(tempDir);// 刪除文件夾
        } else {
         tempDir.mkdirs();
        }
       } catch (Exception e) {
        e.printStackTrace();
       }

       try {
        this.unJar(jarName, tempFileName);// 先解壓目標壓縮Jar文件 到臨時文件夾
        File f = new File(sourceFileName);
       
        if(f.isDirectory()){//如果是文件夾
         FolderCopy.copyDirectiory(sourceFileName, tempFileName+"/"+new File(sourceFileName).getName());// 拷貝源文件到臨時文件夾
        
        }
        if(f.isFile())
         FolderCopy.copyDirectiory(sourceFileName, tempFileName);// 拷貝源文件到臨時文件夾

        this.jar(tempFileName, jarName);// 再壓縮臨時文件夾

        FolderCopy.deleteFile(tempDir); //再刪除臨時文件夾

       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }

    }

    /**
    * 壓縮指定文件夾

    * @param souceFileName
    *            源文件
    * @param destFileName
    *            目標文件
    */
    private void jar(String souceFileName, String destFileName) {
       destName = destFileName;
       File file = new File(souceFileName);
       try {
        jar(file, destFileName);
       } catch (Exception e) {
        e.printStackTrace();
       }
    }

    private void jar(File souceFile, String destFileName) throws IOException {
       FileOutputStream fileOut = null;
       try {
        fileOut = new FileOutputStream(destFileName);
       } catch (FileNotFoundException e) {
        e.printStackTrace();
       }
       JarOutputStream out = new JarOutputStream(fileOut);
       jar(souceFile, out, "");
       out.close();
    }

    String destName = "";

    private void jar(File souceFile, JarOutputStream out, String base)
        throws IOException {

       if (souceFile.isDirectory()) {
        File[] files = souceFile.listFiles();
        out.putNextEntry(new JarEntry(base + "/"));
        base = base.length() == 0 ? "" : base + "/";
        for (File file : files) {
         jar(file, out, base + file.getName());
        }
       } else {
        if (base.length() > 0) {
         out.putNextEntry(new JarEntry(base));
        } else {
         out.putNextEntry(new JarEntry(souceFile.getName()));
        }

        FileInputStream in = new FileInputStream(souceFile);

        int b;
        byte[] by = new byte[1024];
        while ((b = in.read(by)) != -1) {
         out.write(by, 0, b);
        }
        in.close();
       }
    }

    /**
    * 解壓縮文件

    * @param zipFilename
    * @param outputDirectory
    * @throws IOException
    */
    public synchronized void unJar(String jarFilename, String outputDirectory)
        throws IOException {
       File outFile = new File(outputDirectory);
       if (!outFile.exists()) {
        outFile.mkdirs();
       }

       JarFile jarFile = new JarFile(jarFilename);
       Enumeration en = jarFile.entries();
       JarEntry jarEntry = null;
       while (en.hasMoreElements()) {
        jarEntry = (JarEntry) en.nextElement();
        if (jarEntry.isDirectory()) {
         // mkdir directory
         String dirName = jarEntry.getName();
         dirName = dirName.substring(0, dirName.length() - 1);

         File f = new File(outFile.getPath() + File.separator + dirName);
    //    

        } else {
         // unjar file
         File f = new File(outFile.getPath() + File.separator
           + jarEntry.getName());
        
         this.createFile(f);

         InputStream in = jarFile.getInputStream(jarEntry);
         FileOutputStream out = new FileOutputStream(f);
         try {
          int c;
          byte[] by = new byte[1024];
          while ((c = in.read(by)) != -1) {
           out.write(by, 0, c);
          }
          // out.flush();
         } catch (IOException e) {
          e.printStackTrace();
         } finally {
          out.close();
          in.close();
         }
        }
       }
    }

    /**
    * 創建文件 包含不存在的文件夾
    */
    public boolean createFile(File file) {
    //   System.out.println("=="+file.getAbsolutePath());
       if (file == null)
        return false;
       try {
        if (file.isDirectory()&&!file.exists()) {
         file.mkdirs();// 創建目錄
        } else { 
        
         File fileP = new File(file.getParent());
         if(!fileP.exists()){
          fileP.mkdirs();
         }
        
        }
        file.createNewFile();//先確保創建文件夾目錄后創建文件
        return true;
       } catch (Exception e) {
        e.printStackTrace();
        return false;
       }
    }

    /**
    * 把指定文件打包 只能是文件不能文件夾
    */
    public void fileJar() {
       String[] filenames = new String[] { "d:/d.jar", "d:/a.txt" };
       byte[] buf = new byte[1024];
       try {
        // Create the Jar file
        String outFilename = "d:/d.jar";
        JarOutputStream out = new JarOutputStream(new FileOutputStream(
          outFilename));

        for (int i = 0; i < filenames.length; i++) {
         FileInputStream in = new FileInputStream(filenames[i]);

         // Add Jar entry to output stream.
         System.out.println("==" + filenames[i]);
         out.putNextEntry(new JarEntry(filenames[i]));

         // Transfer bytes from the file to the Jar file
         int len;
         while ((len = in.read(buf)) > 0) {
          out.write(buf, 0, len);
         }

         // Complete the entry

         out.closeEntry();
         in.close();
        }

        // Complete the Jar file
        out.close();
       } catch (Exception e) {
        e.printStackTrace();
       }
    }
    }

    posted on 2010-11-19 10:57 Daniel 閱讀(933) 評論(0)  編輯  收藏 所屬分類: CoreJava
    <2025年5月>
    27282930123
    45678910
    11121314151617
    18192021222324
    25262728293031
    1234567

    常用鏈接

    留言簿(3)

    隨筆檔案

    文章分類

    文章檔案

    相冊

    搜索

    •  

    最新評論

    主站蜘蛛池模板: 国产成人精品高清免费| 亚洲高清国产AV拍精品青青草原| 免费无遮挡无遮羞在线看| 亚洲一区二区三区在线播放 | 亚洲熟女综合一区二区三区| 国产精品色午夜免费视频| 香蕉免费看一区二区三区| 亚洲国产成人久久综合一区| 免费国产a国产片高清| 免费观看在线禁片| 亚洲欧美日韩久久精品| 亚洲精品国产美女久久久| 99久久免费国产精品特黄| 一级一片免费视频播放| 亚洲国产精品美女| 久久国产成人精品国产成人亚洲| 亚洲精品456播放| 亚洲免费在线观看视频| 一区二区三区在线免费观看视频| 亚洲精品无码成人AAA片| 免费A级毛片无码无遮挡内射| 日日躁狠狠躁狠狠爱免费视频| 亚洲AV无码国产精品色| 亚洲精品无码久久久久sm| 哒哒哒免费视频观看在线www| 四虎成人精品永久免费AV| 一级做a爰片性色毛片免费网站| 亚洲国产综合人成综合网站00| 不卡一卡二卡三亚洲| 情侣视频精品免费的国产| 最近免费中文字幕大全免费| 国产V片在线播放免费无码| 亚洲av日韩aⅴ无码色老头 | 国产大片免费天天看| 大桥未久亚洲无av码在线| 亚洲美女在线观看播放| 亚洲成a人片在线观看日本| 久久亚洲中文字幕精品一区四| 国产裸模视频免费区无码| 麻豆一区二区免费播放网站| 无码日韩精品一区二区免费暖暖 |