簡體   English   中英

解壓縮文件真的很慢

[英]Unzipping file is really slow

我已經編寫了一些代碼來檢索一個zip文件並將其解壓縮為Directoy。 該zip文件包含兩個文件夾,並且根據每個文件所在的文件夾,將其解壓縮到該目錄的文件夾中。

但是,該代碼需要很長時間才能運行(大約10分鍾)。 雖然,每個文件夾包含近1000個文件,並且zip文件的總大小為5000kb。 我認為它運行緩慢,因為每次進入循環時我都會創建FileOutputStream和InputStream。 但是,我需要這樣做,因為直到從zip文件中讀取文件之前,我都不知道文件的輸出目錄。 (即找出它所在的文件夾)

有什么建議么?

/**
 * Retrieves and unzips a file from its URL
 */
public void retrieveFiles(String URL) {

    //Retrieve file from URL
    File zip = new File(getFile(URL));
    zip.mkdirs();

    try {
        //Create .zip file from file directory
        ZipFile zipFile = new ZipFile(zip);
        Enumeration<? extends ZipEntry> enumeration = zipFile.entries();

        //While zip file contains elements, get the next zipped file
        while (enumeration.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();

            //Ignore folders and other zip files
            if(!zipEntry.isDirectory() && !zipEntry.getName().endsWith(".zip")){

                //Find directory and filename for new unzipped file
                String directory = getURL(zipEntry.getName());
                String fileName = getFileName(zipEntry.getName());
                String fullDirectory = createDirectory(directory, fileName);

                //Unzip file and store in directory
                System.out.println("Unzipping file: " + fileName);
                FileOutputStream fout = new FileOutputStream(fullDirectory);
                InputStream in = zipFile.getInputStream(zipEntry);
                for (int c = in.read(); c != -1; c = in.read()) {
                    fout.write(c);
                }
                zipFile.getInputStream(zipEntry).close();
                in.close();
                fout.close();
            }
        }
        zipFile.close();
        System.out.println("Unzipping complete!");

        zip.delete();

    } catch (IOException e) {
        System.out.println("Unzip failed");
        e.printStackTrace();
    }
}

您一次要復制一個字節的文件

for (int c = in.read(); c != -1; c = in.read())
    fout.write(c);
}

您可以嘗試使用Apaches org.apache.commons.io.IOUtils.copy(),因為這將分批復制並使用NIO和其他改進。 您可以在commons-io.jar中找到它

嘗試先將文件加載到內存中,一次將X mb加載到內存中,然后創建IO流到文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM