java 解压文件(使用WinRAR软件)

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipInputStream;

 

public class Unzip {

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();

}

 

}

 

public void unRarFile(String targetPath, String absolutePath) {

 

try {

File tar = new File(targetPath);

if(!tar.exists()){

tar.getParentFile().mkdirs();

tar.mkdir();

}

// 系统安装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);

rt.exec(unrarCmd);

} catch (Exception e) {

System.out.println("解压发生异常");

}

}

 

/**

 * @param args

 */

public static void main(String[] args) {

String targetPath = "d:/test1";

String rarFilePath = "E:/a.zip";

Unzip unrar = new Unzip();

unrar.unRarFile(targetPath, rarFilePath);

}

}

你可能感兴趣的:(java)