2015-10-29 68 views
0

我正在寫一個java程序,它將提取zip文件並將其中的文件重命名爲zip文件名。例如:zip文件的名稱是zip.zip,其中的文件是content.txt。在這裏我想提取zip文件,content.txt必須重命名爲zip.txt。我正在嘗試下面的程序。如何重命名提取的文件

這裏會有zip文件

只有一個文件Zip.Java

import java.io.BufferedOutputStream; 
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; 

public class zip { 
    private static final int BUFFER_SIZE = 4096; 

    public void unzip(String zipFilePath, String destDirectory) throws IOException { 
     File destDir = new File(destDirectory); 
     if (!destDir.exists()) { 
      destDir.mkdir(); 
     } 
     ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); 
     ZipEntry entry = zipIn.getNextEntry(); 
     while (entry != null) { 
      String filePath = destDirectory + File.separator + entry.getName(); 
      if (!entry.isDirectory()) { 
       // if the entry is a file, extracts it 
       extractFile(zipIn, filePath, zipFilePath); 
      } else { 
       // if the entry is a directory, make the directory 
       File dir = new File(filePath); 
       dir.mkdir(); 
      } 
      zipIn.closeEntry(); 
      entry = zipIn.getNextEntry(); 
     } 
     zipIn.close(); 
    } 

    private void extractFile(ZipInputStream zipIn, String filePath, String zipFilePath) throws IOException { 
     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); 

     byte[] bytesIn = new byte[BUFFER_SIZE]; 
     int read = 0; 
     while ((read = zipIn.read(bytesIn)) != -1) { 
      bos.write(bytesIn, 0, read); 
     } 
     File oldName = new File(filePath); 
     System.out.println(oldName); 
     String str = zipFilePath.substring(zipFilePath.lastIndexOf("\\") + 1, zipFilePath.lastIndexOf(".")); 
     System.out.println(str); 
     File zipPath = new File(zipFilePath); 
     System.out.println(zipPath.getParent()); 
     File newName = new File(zipPath.getParent() + "\\" + str); 
     System.out.println(newName); 
     if (oldName.renameTo(newName)) { 
      System.out.println("Renamed"); 
     } else { 
      System.out.println("Not Renamed"); 
     } 

     bos.close(); 
    } 

} 

UnZip.Java

public class UnZip { 
    public static void main(String[] args) { 
     String zipFilePath = "C:\\Users\\u0138039\\Desktop\\Proview\\Zip\\New Companies Ordinance (Vol Two)_xml.zip"; 
     String destDirectory = "C:\\Users\\u0138039\\Desktop\\Proview\\Zip"; 
     zip unzipper = new zip(); 
     try { 
      unzipper.unzip(zipFilePath, destDirectory); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

在這裏,我能提取該文件但無法重命名它。請讓我知道我在哪裏出錯,以及如何解決它。

感謝

回答