2012-08-10 45 views
3

就是這樣。我有一個文本文件,我需要將它移動到給定目錄中的(現有)Zip文件中。Java - 如何將文件移動到zip文件中?

File file = new File("C:\\afolder\\test.txt"); 
    File dir = new File(directoryToGo+"existingzipfile.zip"); 
    boolean success = file.renameTo(new File(dir, file.getName())); 

但它不起作用。有沒有辦法將文件移動到現有的Zip文件中? 謝謝。

+2

可能重複:http://stackoverflow.com/questions/3048669/how-can-i-add-entries-to-an-existing-zip-file-in-java – Sujay 2012-08-10 16:50:54

+0

它不會是近那很簡單。 Java提供了用於管理'java.util.zip'中壓縮歸檔的類,特別是['ZipFile'](http://docs.oracle.com/javase/6/docs/api/java/util/zip/ZipFile.html )。看[這個答案](http://stackoverflow.com/a/3048744/275567)。 – pb2q 2012-08-10 16:51:06

回答

4

嗯,你可以使用類似:

public static void addFilesToExistingZip(File zipFile, File[] files) throws IOException { 
    // get a temp file 
    File tempFile = File.createTempFile(zipFile.getName(), null); 
    // delete it, otherwise you cannot rename your existing zip to it. 
    tempFile.delete(); 
    boolean renameOk = zipFile.renameTo(tempFile); 
    if (!renameOk) { 
     throw new RuntimeException(
       "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath()); 
    } 
    byte[] buf = new byte[1024]; 
    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); 
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); 
    ZipEntry entry = zin.getNextEntry(); 
    while (entry != null) { 
     String name = entry.getName(); 
     boolean notInFiles = true; 
     for (File f : files) { 
      if (f.getName().equals(name)) { 
       notInFiles = false; 
       break; 
      } 
     } 
     if (notInFiles) { // Add ZIP entry to output stream. 
      out.putNextEntry(new ZipEntry(name)); // Transfer bytes from the ZIP file to the output file 
      int len; 
      while ((len = zin.read(buf)) > 0) { 
       out.write(buf, 0, len); 
      } 
     } 
     entry = zin.getNextEntry(); 
    } // Close the streams 
    zin.close(); // Compress the files 
    for (int i = 0; i < files.length; i++) { 
     InputStream in = new FileInputStream(files[i]); // Add ZIP entry to output stream. 
     out.putNextEntry(new ZipEntry(files[i].getName())); // Transfer bytes from the file to the ZIP file 
     int len; 
     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } // Complete the entry 
     out.closeEntry(); 
     in.close(); 
    } // Complete the ZIP file 
    out.close(); 
    tempFile.delete(); 
} 

參考:

+0

順便說一句我剛剛學會了將兩個相同名稱的ZipEntry對象添加到ZipOutputStream中的難題,會引發異常。所以添加文件時要小心你已經擁有的文件。 – 2014-09-10 19:57:45

2

你需要建立一個新的zip文件:

  • 打開現有的ZIP文件進行閱讀
  • 打開一個新的zip文件從舊的zip文件寫入
  • 複製的所有條目新的一個,忽略對應的額外的文件項時,如果有一個
  • 添加您額外的文件
  • 關閉輸入和輸出文件
  • 刪除舊的zip文件
  • 新的zip文件重命名爲舊的名字
+0

謝謝。但如果zip文件實際上是一個jar文件呢? – user1541106 2012-08-10 17:00:25

+1

罐子是zip文件。它應該工作一樣。 – 2012-08-10 17:01:38

1

你可以這樣做,在這裏uploadPath+fileName是文件名,其路徑:

String FileName="Urzip file name. zip"; 

FileOutputStream outputStream = new FileOutputStream(uploadPath+fileName); 
ZipOutputStream zipFile = new ZipOutputStream(outputStream); 

byte[] buffer = new byte[1024]; 

// Then, here I have list of pdf files in a LIST: 

// continuation ... 
for (int i = 0; i < filename.size(); i++) { 
    String file = filename.get(i); 
    FileInputStream input = new FileInputStream(uploadPath+file); 
    ZipEntry entry = new ZipEntry(file); 
    zipFile.putNextEntry(entry); 
    int len; 

    while ((len = input.read(buffer)) > 0) { 
     zipFile.write(buffer, 0, len); 
    } 

    zipFile.closeEntry(); 
    input.close(); 
} 

// Next, here "downFile" is the other file which you have to add in your existing zip: 

// continuation ... 
FileInputStream input = new FileInputStream(uploadPath+downFile); 

ZipEntry e = new ZipEntry(downFile); 
zipFile.putNextEntry(e); 
int len; 
while ((len = input.read(buffer)) > 0) { 
    zipFile.write(buffer, 0, len); 
} 
zipFile.closeEntry(); 
input.close(); 

zipFile.close(); 
+1

請在鍵盤上修復丟失鍵的問題 - 像_y_ - ;) – kleopatra 2012-11-28 11:10:09

+0

好奇:你爲什麼要堅持把非代碼插入代碼段?這使得很難通過C&P使用片段... – kleopatra 2012-11-28 11:57:14

0

與Java 7開始,你有一個zip文件系統的供應商,它允許你寫這樣的代碼:

final Path src = Paths.get("c:\\afolder\\test.txt"); 
final String filename = src.getFileName().toString(); 

final Path zip = Paths.get(directoryToGo, "existingzipfile.zip"); 
final URI uri = URI.create("jar:" + zip.toUri()); 
final Map<String, ?> env = Collections.emptyMap(); 

try (
    final FileSystem zipfs = FileSystems.newFileSystem(uri, env); 
) { 
    Files.move(src, zipfs.getPath("/" + filename), 
     StandardCopyOption.REPLACE_EXISTING); 
} 
0

添加類根據接受的答案將文件移動到jar/zip文件夾內。 接受的答案並不包含完整的可執行代碼,所以我添加了幫助將文件移動/複製到jar/zip的類 package ZipReader;

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipInputStream; 
import java.util.zip.ZipOutputStream; 

public class ZipWrite { 
    public static void main(String args[]) throws IOException 
    { 
     File file=new File("F:/MyProjects/New folder/mysql-connector-java-5.1.18-bin.jar"); 
     File filetoPush=new File("F:/MyProjects/New folder/BestResponseTimeBalanceStrategy.class"); 
     File[] files=new File[1]; 
     files[0]=filetoPush; 
     addFilesToExistingZip(file,files); 
    } 

    public static void addFilesToExistingZip(File zipFile, File[] files) 
      throws IOException { 
     // get a temp file 
     File tempFile = File.createTempFile(zipFile.getName(), null); 
     // delete it, otherwise you cannot rename your existing zip to it. 
     tempFile.delete(); 
     boolean renameOk = zipFile.renameTo(tempFile); 
     if (!renameOk) { 
      throw new RuntimeException("could not rename the file " 
        + zipFile.getAbsolutePath() + " to " 
        + tempFile.getAbsolutePath()); 
     } 
     byte[] buf = new byte[1024]; 
     ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); 
     ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); 
     ZipEntry entry = zin.getNextEntry(); 
     while (entry != null) { 
      String name = entry.getName(); 

      boolean notInFiles = true; 
      for (File f : files) { 
       if (f.getName().equals(name)) { 
        System.out.println(name); 
        notInFiles = false; 
        break; 
       } 
      } 

      if (notInFiles) { 
       System.out.println("adding"); 
       // Add ZIP entry to output stream. 
       out.putNextEntry(new ZipEntry(name)); // Transfer bytes from the 
                 // ZIP file to the 
                 // output file 
       int len; 
       while ((len = zin.read(buf)) > 0) { 
        out.write(buf, 0, len); 
       } 
      } 
      entry = zin.getNextEntry(); 
     } // Close the streams 
     zin.close(); // Compress the files 
     for (int i = 0; i < files.length; i++) { 
      FileInputStream in = new FileInputStream(files[i]); 
      // Add ZIP entry to output stream. 
      System.out.println("files[i].getName()-->"+files[i].getName()); 
      out.putNextEntry(new ZipEntry("com/mysql/jdbc/util/"+files[i].getName())); 
      // Transfer bytes from the file to the ZIP file 
      int len; 
      while ((len = in.read(buf)) > 0) { 
       out.write(buf, 0, len); 
      } 
      // Complete the entry 
      out.closeEntry(); 
      in.close(); 
     } 
     // Complete the ZIP file 
     out.close(); 
     tempFile.delete(); 
    } 

} 
+0

請添加對此代碼的示例的說明。 – cybermonkey 2015-03-11 17:47:55

相關問題