java解归档tar文件

版权声明:自由转载,无需过问 https://blog.csdn.net/Next__One/article/details/78668876

首先要在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();
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/Next__One/article/details/78668876