java解歸檔tar文件

首先要在maven上找到https://mvnrepository.com/artifact/javatar/javatar
jar包,下面是座標:

<dependency>
    <groupId>javatar</groupId>
    <artifactId>javatar</artifactId>
    <version>2.5</version>
</dependency>

解歸檔代碼:

/**
     * 
     * @param src 
     * 解壓單個文件 解壓後的文件存放在tar文件目錄下
     */
    public static void extTarFileList(File src) {  
        if(!src.exists() ) return;
        OutputStream out = null;  
        TarInputStream in = null;
        try {  
            String parent = src.getParentFile().getAbsolutePath();
            in = new TarInputStream(new FileInputStream(src));  
            TarEntry entry = null;  
            while ((entry = in.getNextEntry()) != null) {  
                if (entry.isDirectory()) {  
                    continue;  
                }  
                String dest = parent + entry.getName();
                File outfile = new File(dest);  
                out = new BufferedOutputStream(new FileOutputStream(outfile));  
                int len = -1;  
                byte[] buf = new byte[1024*10];
                while ((len = in.read(buf)) != -1) {  
                    out.write(buf,0,len);  
                }  
                out.flush();
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally{
            close(out,in);
        }
    }  

    public static void close(Closeable ...io){
        for (Closeable temp : io) {
            try {
                if(temp != null){
                    temp.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章