當前位置:才華齋>IT認證>SUN認證>

如何在java中解壓zip和rar檔案

SUN認證 閱讀(6.78K)

為了方便廣大的程式設計師朋友,下面講一講如何在java中實現對zip和rar檔案的解壓,一起和小編來看看吧!

如何在java中解壓zip和rar檔案

  一、解壓rar檔案。

由於WinRAR 是共享軟體,並不是開源的,所以解壓rar檔案的前提是系統已經安裝了winrar,比如本人的安裝路徑是:

C:Program FilesWinRAR

然後運用ess 的.相關知識來執行系統命令列來實現解壓的。

winrar 命令列相關引數自己可以搜尋下的網上資料很多

具體程式碼:

Java程式碼

**

* 解壓rar檔案(需要系統安裝Winrar 軟體)

* @author Michael sun

*/

public class UnRarFile {

/**

* 解壓rar檔案

*

* @param targetPath

* @param absolutePath

*/

public void unRarFile(String targetPath, String absolutePath) {

try {

// 系統安裝winrar的路徑

String cmd = "C:Program FilesWinRAR";

String unrarCmd = cmd + " x -r -p- -o+ " + absolutePath + " "

+ targetPath;

Runtime rt = untime();

Process pre = (unrarCmd);

InputStreamReader isr = new InputStreamReader(nputStream());

BufferedReader bf = new BufferedReader(isr);

String line = null;

while ((line = Line()) != null) {

line = ();

if (""ls(line)) {

continue;

}

tln(line);

}

e();

} catch (Exception e) {

tln("解壓發生異常");

}

}

/**

* @param args

*/

public static void main(String[] args) {

String targetPath = "D:testunrar";

String rarFilePath = "D:test";

UnRarFile unrar = new UnRarFile();

rFile(targetPath, rarFilePath);

}

}

  二、解壓zip檔案

由於zip是免費的,所以在jdk裡提供了相應的類對zip檔案的實現:

.*,詳細情況可以參考java API

Java程式碼

/**

* 解壓zip檔案

* @author Michael sun

*/

public class UnzipFile {

/**

* 解壓zip檔案

*

* @param targetPath

* @param zipFilePath

*/

public void unzipFile(String targetPath, String zipFilePath) {

try {

File zipFile = new File(zipFilePath);

InputStream is = new FileInputStream(zipFile);

ZipInputStream zis = new ZipInputStream(is);

ZipEntry entry = null;

tln("開始解壓:" + ame() + "...");

while ((entry = extEntry()) != null) {

String zipPath = ame();

try {

if (rectory()) {

File zipFolder = new File(targetPath + rator

+ zipPath);

if (!ts()) {

rs();

}

} else {

File file = new File(targetPath + rator

+ zipPath);

if (!ts()) {

File pathDir = arentFile();

rs();

teNewFile();

}

FileOutputStream fos = new FileOutputStream(file);

int bread;

while ((bread = ()) != -1) {

e(bread);

}

e();

}

tln("成功解壓:" + zipPath);

} catch (Exception e) {

tln("解壓" + zipPath + "失敗");

continue;

}

}

e();

e();

tln("解壓結束");

} catch (Exception e) {

tStackTrace();

}

}

/**

* @param args

*/

public static void main(String[] args) {

String targetPath = "D:testunzip";

String zipFile = "D:test";

UnzipFile unzip = new UnzipFile();

pFile(targetPath, zipFile);

}

}