posts - 1,  comments - 25,  trackbacks - 0

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

          1.創(chuàng)建臨時(shí)文件

          2..先解壓目標(biāo)壓縮Jar文件 到臨時(shí)文件夾

          3.拷貝源文件到臨時(shí)文件夾

          4.再壓縮臨時(shí)文件夾

          5.再刪除臨時(shí)文件夾

          方法可能有些笨,但是我找了好久也沒(méi)找到現(xiàn)成API實(shí)現(xiàn)這個(gè)功能。所以和大家分享,共寫(xiě)了三個(gè)類

          第一個(gè)類:

          package com.jar;

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

          /**
          * 測(cè)試主程序
          */
          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);
          }
          /**
          * 文件夾拷貝,將源文件夾下的所有文件及其子文件夾(文件)拷貝到目標(biāo)文件夾(文件)下

          * @param sourceFile
          *            源文件夾或文件
          * @param desFile
          *            目標(biāo)文件夾
          * @return
          */
          public static boolean copyDirectiory(String sourceFile, String desFile)
              throws IOException {
             File des = new File(desFile);
             if (!des.exists())
              des.mkdirs();// 不存在目標(biāo)文件夾就創(chuàng)建
            
             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()) { // 如果是文件 則讀源文件 寫(xiě)入目標(biāo)文件
               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); // 向目標(biāo)文件寫(xiě)文件
               }
               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'); 
               } 
             }


          }

          第二個(gè)類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/瘋狂農(nóng)場(chǎng)", "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
          *            要添加的文件或文件夾

          *            遍歷文件夾 拼寫(xiě)批處理命令
          */
          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;
          }
          }

          第三個(gè)類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
          *            要壓縮到指定目標(biāo)壓縮文件的源文件或文件夾
          * @param destFileName
          *            目標(biāo)壓縮文件
          * @throws IOException
          */
          public void fileAddToJar(String sourceFileName, String jarName) {
          //   System.out.println("**=="+sourceFileName);
             // 先解壓到臨時(shí)文件夾,存在先刪除 不存在直接創(chuàng)建
             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);// 先解壓目標(biāo)壓縮Jar文件 到臨時(shí)文件夾
              File f = new File(sourceFileName);
             
              if(f.isDirectory()){//如果是文件夾
               FolderCopy.copyDirectiory(sourceFileName, tempFileName+"/"+new File(sourceFileName).getName());// 拷貝源文件到臨時(shí)文件夾
              
              }
              if(f.isFile())
               FolderCopy.copyDirectiory(sourceFileName, tempFileName);// 拷貝源文件到臨時(shí)文件夾

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

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

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

          }

          /**
          * 壓縮指定文件夾

          * @param souceFileName
          *            源文件
          * @param destFileName
          *            目標(biāo)文件
          */
          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();
               }
              }
             }
          }

          /**
          * 創(chuàng)建文件 包含不存在的文件夾
          */
          public boolean createFile(File file) {
          //   System.out.println("=="+file.getAbsolutePath());
             if (file == null)
              return false;
             try {
              if (file.isDirectory()&&!file.exists()) {
               file.mkdirs();// 創(chuàng)建目錄
              } else { 
              
               File fileP = new File(file.getParent());
               if(!fileP.exists()){
                fileP.mkdirs();
               }
              
              }
              file.createNewFile();//先確保創(chuàng)建文件夾目錄后創(chuàng)建文件
              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 閱讀(936) 評(píng)論(0)  編輯  收藏 所屬分類: CoreJava
          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          常用鏈接

          留言簿(3)

          隨筆檔案

          文章分類

          文章檔案

          相冊(cè)

          搜索

          •  

          最新評(píng)論

          主站蜘蛛池模板: 和田市| 新巴尔虎左旗| 分宜县| 买车| 得荣县| 乳源| 齐河县| 桂林市| 马龙县| 灵武市| 讷河市| 木兰县| 安泽县| 固阳县| 松原市| 伊春市| 南皮县| 客服| 鹿泉市| 施秉县| 万宁市| 广丰县| 新竹县| 台山市| 陵川县| 遂溪县| 克山县| 习水县| 延吉市| 留坝县| 苏尼特右旗| 西青区| 沂源县| 绿春县| 乌什县| 常熟市| 胶州市| 闽清县| 永嘉县| 利川市| 兴国县|