- package test;
-
- import java.io.File;
- import java.io.FileOutputStream;
-
- import de.innosystec.unrar.Archive;
- import de.innosystec.unrar.rarfile.FileHeader;
-
- public class UnRarFile {
-
- /**
- * 解壓rar格式壓縮包。
- * 對應的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又會用到commons-logging-1.1.1.jar
- */
- private static void unRarFile(String srcRar,String desDir){
- if(!srcRar.trim().toLowerCase().endsWith(".rar")){
- System.out.println("非rar文件");
- return ;
- }
- File dir=new File(desDir);
- if(!dir.exists()){
- dir.mkdirs();
- }
- Archive a=null; //代表一個壓縮文件
- try {
- a=new Archive(new File(srcRar));
- if(null!=a){
- a.getMainHeader().print();//打印文件信息
- FileHeader fh=a.nextFileHeader();
- while(null!=fh){
- if(fh.isDirectory()){//文件夾
- File fol=new File(desDir+File.separator+fh.getFileNameString());
- fol.mkdirs();
- }else{
- File out=new File(desDir+File.separator+fh.getFileNameString().trim());
- System.out.println(out.getAbsolutePath());
- try{
- if(!out.exists()){
- if(!out.getParentFile().exists()){
- out.getParentFile().mkdirs();
- }
- out.createNewFile();
- }
- FileOutputStream os=new FileOutputStream(out);
- a.extractFile(fh, os);
- os.close();
- }catch (Exception e) {
- }
- }
- fh=a.nextFileHeader();
- }
- a.close();
- }
- } catch (Exception e) {
- }
- }
-
- public static void main(String[] args) {
- File file=new File("D:\\test");
- for(File f:file.listFiles()){
- UnRarFile.unRarFile("D:\\test\\"+f.getName(),"D:\\test\\"+f.getName().replaceAll(".rar",""));
- }
- }
- }
|