天天看點

java zip壓縮慢_Java開發之淺談ZIP壓縮中要注意的幾點

前言

ZIP,是一個檔案的壓縮的算法。ZIP通常使用字尾名“.zip”,它的MIME格式為 application/zip 。目前,ZIP格式屬于幾種主流的壓縮格式之一,其競争者包括RAR格式以及開放源碼的7-Zip格式。從性能上比較,RAR格式較ZIP格式壓縮率較高,但是它的壓縮時間遠遠高于Zip。

java zip壓縮慢_Java開發之淺談ZIP壓縮中要注意的幾點

在日常java開發中,經常會用到将一個檔案夾或檔案夾中的内容壓縮成一個zip包,這裡我們就從以下幾個需要注意的事項入手,談一談java如何開發zip壓縮類。

zip壓縮注意事項

1 判斷目前伺服器是Windows伺服器還是Linux伺服器

我們知道,目前伺服器的作業系統的兩大主流是windows伺服器和linux伺服器,對于不同的伺服器,zip壓縮軟體的安裝路徑可能不同,如Windows上可能配有winrar,而winrar會極大的提高壓縮效果;而linux伺服器呢,可能會安裝有zip而可以使用zip指令壓縮,也比java自有的類速度要快很多。那麼如何區分目前系統是Windows系統還是Linux系統呢?

Properties props=System.getProperties();

if(props.getProperty("os.name").indexOf("Linux")>-1){

//這裡可以執行Linux裡面的操作

}else if(props.getProperty("os.name").indexOf("Windows")>-1){

//這裡可以執行Linux裡面的操作

}

2.Windows系統下如何調用winrar壓縮軟體進行zip壓縮

java zip壓縮慢_Java開發之淺談ZIP壓縮中要注意的幾點

public static boolean winrar(String winrarfile, String folder) {

String rarPath = "C:\\Program Files\\WinRAR\\WinRAR.exe";

File winrarFile=new File(rarPath);

if(winrarFile.isFile()&&winrarFile.exists()){

String cmd="";

cmd = rarPath + " a -ep1 " + winrarfile + " "+ folder;

try {

Process proc = Runtime.getRuntime().exec(cmd);

if (proc.waitFor() != 0) {

if (proc.exitValue() == 0)

return true;

}

} catch (Exception e) {

e.printStackTrace();

}

}

return false;

}

3.Linux下調用zip指令進行zip壓縮

該處需要注意,首先應在Linux伺服器上安裝zip,可以使用指令:yum -y install zip;

public static boolean linuxZip(String zipfile, String folder){

try {

File file=new File(folder);

if(!file.exists())

{

return false;

}

if(file.isDirectory()&&file.listFiles().length==0)

{

return false;

}

Process proc = Runtime.getRuntime().exec(new String[] { "/bin/csh", "-c","cd "+folder+";zip -r "+zipfile +" ./*" });

if (proc.waitFor() != 0) {

if (proc.exitValue() == 0)

return true;

}

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

4.注意壓縮采用的編碼,避免亂碼現象

ZipOutputStream zos = new ZipOutputStream(new File(zipFileName));

zos.setEncoding("gb2312");

這裡如果壓縮後檔案夾内中文檔案名出現亂碼,嘗試修改gb2312為utf-8等别的編碼,可有效解決亂碼問題。

結語

如果您在開發過程中遇到有關zip的壓縮問題,不妨在下方留言,大家一起來應對助您解決問題。如果感覺本文對您有幫助,請收藏并轉發。