靜網PWA視頻評論

如何在java中解壓zip和rar文件

2024年01月04日

- txt下載

如何在java中解壓zip和rar文件
為了方便廣大的程式設計師朋友,下面講一講如何在java中實現對zip和rar文件的解壓,一起和小編來看看吧!
  一、解壓rar文件。
由於WinRAR 是共享軟體,並不是開源的,所以解壓rar文件的前提是系統已經安裝了winrar,比如本人的安裝路徑是:
C:\\Program Files\\WinRAR\\winrar.exe
然後運用java.lang.Process 的.相關知識來運行系統命令行來實現解壓的。
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 Files\\WinRAR\\winrar.exe";
String unrarCmd = cmd + " x -r -p- -o+ " + absolutePath + " "
+ targetPath;
Runtime rt = Runtime.getRuntime();
Process pre = rt.exec(unrarCmd);
InputStreamReader isr = new InputStreamReader(pre.getInputStream());
BufferedReader bf = new BufferedReader(isr);
String line = null;
while ((line = bf.readLine()) != null) {
line = line.trim();
if ("".equals(line)) {
continue;
}
System.out.println(line);
}
bf.close();
} catch (Exception e) {
System.out.println("解壓發生異常");
}
}
/**
* @param args
*/
public static void main(String[] args) {
String targetPath = "D:\\test\\unrar\\";
String rarFilePath = "D:\\test\\test.rar";
UnRarFile unrar = new UnRarFile();
unrar.unRarFile(targetPath, rarFilePath);
}
}
  二、解壓zip文件
由於zip是免費的,所以在jdk里提供了相應的類對zip文件的實現:
java.util.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;
System.out.println("開始解壓:" + zipFile.getName() + "...");
while ((entry = zis.getNextEntry()) != null) {
String zipPath = entry.getName();
try {
if (entry.isDirectory()) {
File zipFolder = new File(targetPath + File.separator
+ zipPath);
if (!zipFolder.exists()) {
zipFolder.mkdirs();
}
} else {
File file = new File(targetPath + File.separator
+ zipPath);
if (!file.exists()) {
File pathDir = file.getParentFile();
pathDir.mkdirs();
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
int bread;
while ((bread = zis.read()) != -1) {
fos.write(bread);
}
fos.close();
}
System.out.println("成功解壓:" + zipPath);
} catch (Exception e) {
System.out.println("解壓" + zipPath + "失敗");
continue;
}
}
zis.close();
is.close();
System.out.println("解壓結束");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
String targetPath = "D:\\test\\unzip";
String zipFile = "D:\\test\\test.zip";
UnzipFile unzip = new UnzipFile();
unzip.unzipFile(targetPath, zipFile);
}
}

收藏

相關推薦

清純唯美圖片大全

字典網 - 試題庫 - 元問答 - 简体 - 頂部

Copyright © cnj8 All Rights Reserved.