2015-02-06 20 views
-1

我想在java中編寫一個應用程序,它可以將一個文件夾打包到一個zip文件中。用戶必須使用JFileChooser選擇文件夾。當我嘗試打包時,它只是創建一個zip包與連接到它應該是的文件夾。請你能告訴我爲什麼以及如何解決它?Java應用程序創建只有連詞的ZipFile

LOLZ搞笑編程社區,我不得不添加"\\"代替"/"而獲得前綴長度..

import java.io.*; 
import java.util.zip.*; 
import javax.swing.*; 
import javax.swing.JFileChooser; 

public class Zipper { 

int prefixLength; 
    ZipOutputStream zipOut; 
    byte[] ioBuffer = new byte[4096]; 

    public Zipper(String dirFileName, String dirFileOutput) throws Exception 
    { 
    prefixLength = dirFileName.lastIndexOf("/") + 1; 
    zipOut = new ZipOutputStream(new FileOutputStream(dirFileOutput + ".zip")); 
    createZipFrom(new File(dirFileName)); 
    zipOut.close(); 
    } 

    void createZipFrom(File dir) throws Exception 
    { if (dir.exists() && dir.canRead() && dir.isDirectory()) 
    { File[] files = dir.listFiles(); 
     if (files != null) 
     { for (File file: files) 
     { if (file.isDirectory()) 
      { createZipFrom(file); 
      } 
      else 
      { String filePath = file.getAbsolutePath(); 
      FileInputStream in = new FileInputStream(filePath); 
      zipOut.putNextEntry(new ZipEntry(filePath.substring(prefixLength))); 
      int bytesRead; 
      while ((bytesRead = in.read(ioBuffer)) > 0) 
      { zipOut.write(ioBuffer, 0, bytesRead); 
      } 
      System.out.println(filePath + " added\n"); 
      zipOut.closeEntry(); 
      in.close(); 
      } 
     } 
     } 
    } 
    } 

    public static void main(String[] args) throws Exception { 

JFileChooser chooser = new JFileChooser(); 
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
chooser.showSaveDialog(null); 

String path=chooser.getSelectedFile().getAbsolutePath(); 
String dirFileName=chooser.getSelectedFile().getAbsolutePath(); 

    String dirFileOutput = JOptionPane.showInputDialog(null, "packetname"); // thats working.. 

    System.out.println(dirFileName); 
    System.out.println(dirFileOutput); 

    new Zipper(dirFileName, dirFileOutput); 

    System.out.println("package " + dirFileOutput + "." + ".zip created\n"); 

    } 

} 
+0

您是否嘗試過使用調試器來找出是什麼問題呢? – Jens 2015-02-06 12:53:37

+0

我想我試過..我只是試圖輸出到命令行。你的意思是調試?文件名似乎是正確的唯一的事情是,文件名與「\」而不是「/」可能是問題? – muni 2015-02-06 12:56:30

+0

那麼你會建議什麼? – muni 2015-02-06 13:20:53

回答

0

我寫使用NIO.2文件API,這使得一個荏苒一些實用方法文件夾容易。該庫是開源的。也許你覺得它很有用。

教程:http://www.softsmithy.org/lib/0.4/docs/tutorial/nio-file/index.html#AddZipResourceSample

的Javadoc:http://www.softsmithy.org/lib/0.4/docs/api/softsmithy-lib-core/index.html

Maven的座標:http://search.maven.org/#artifactdetails|org.softsmithy.lib|softsmithy-lib-core|0.4|bundle

+0

非常感謝,但那不是問題。當我使用控制檯或JDialog的直接輸入時,我可以壓縮它。它只是不使用JFileChooser。 – muni 2015-02-06 13:17:08

相關問題