使用JUnrar提取文件

时间:2010-11-29 14:51:24

标签: java compression

之前我问过一个关于在Java中提取RAR档案的问题,有人向我指出了JUnrar。官方网站已经关闭,但它似乎被广泛使用,因为我在网上发现了很多关于它的讨论。

有人可以告诉我如何使用JUnrar提取存档中的所有文件吗?我在网上找到了一个小片段,但似乎没有用。它将存档中的每个项目显示为目录,即使它是文件。

    Archive rar = new Archive(new File("C://Weather_Icons.rar"));
    FileHeader fh = rar.nextFileHeader();

    while(fh != null){
        if (fh.isDirectory()) {
             logger.severe("directory: " + fh.getFileNameString() ); 
        }

        //File out = new File(fh.getFileNameString());
        //FileOutputStream os = new FileOutputStream(out);
        //rar.extractFile(fh, os);
        //os.close();
        fh=rar.nextFileHeader();

    }

感谢。

1 个答案:

答案 0 :(得分:15)

您也可以查看this代码段。其副本可在下面找到。

public class MVTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String filename = "/home/rogiel/fs/home/movies/vp.mp3.part1.rar";
        File f = new File(filename);
        Archive a = null;
        try {
            a = new Archive(new FileVolumeManager(f));
        } catch (RarException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (a != null) {
            a.getMainHeader().print();
            FileHeader fh = a.nextFileHeader();
            while (fh != null) {
                try {
                    File out = new File("/home/rogiel/fs/test/"
                            + fh.getFileNameString().trim());
                    System.out.println(out.getAbsolutePath());
                    FileOutputStream os = new FileOutputStream(out);
                    a.extractFile(fh, os);
                    os.close();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (RarException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                fh = a.nextFileHeader();
            }
        }
    }
}