1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > bz2解压命令_Java压缩技术 - tar.bz2解压缩

bz2解压命令_Java压缩技术 - tar.bz2解压缩

时间:2020-02-10 05:47:15

相关推荐

bz2解压命令_Java压缩技术 - tar.bz2解压缩

前言

从网络上下载的源码包,最常见的是tar.gz包,还有一部分是tar.bz2包,这篇文章以解压tar.bz2文件为示例来讲解Java的解压操作。

.tar: 打包

.bz2: 由具有高压缩率的压缩工具bzip2压缩

linux中的压缩和解压命令:

压缩:

tar -cjf test.tar.bz2 test

解压:

tar -jxvf test.tar.bz2

准备

由于需要使用TarInputStream类,在pom.xml中增加如下依赖:

<dependency><groupId>org.apache.ant</groupId><artifactId>ant</artifactId><version>1.9.7</version></dependency>

由于需要使用BZip2CompressorInputStream类,在pom.xml中增加如下依赖:

<dependency><groupId>mons</groupId><artifactId>commons-compress</artifactId><version>1.18</version></dependency>

tar.bz2文件解压

创建目录:

/*** 构建目录* @param outputDir 输出目录* @param subDir 子目录*/private static void createDirectory(String outputDir, String subDir){File file = new File(outputDir);if(!(subDir == null || subDir.trim().equals(""))) {//子目录不为空file = new File(outputDir + File.separator + subDir);}if(!file.exists()){if(!file.getParentFile().exists()){file.getParentFile().mkdirs();}file.mkdirs();}}

解压缩tar.bz2文件

/*** 解压缩tar.bz2文件* @param file 压缩包文件* @param targetPath 目标文件夹* @param delete 解压后是否删除原压缩包文件*/public static void decompressTarBz2(File file, String targetPath, boolean delete){FileInputStream fis = null;OutputStream fos = null;BZip2CompressorInputStream bis = null;TarInputStream tis = null;try {fis = new FileInputStream(file);bis = new BZip2CompressorInputStream(fis);tis = new TarInputStream(bis, 1024 * 2);// 创建输出目录createDirectory(targetPath, null);TarEntry entry;while((entry = tis.getNextEntry()) != null){if(entry.isDirectory()){createDirectory(targetPath, entry.getName()); // 创建子目录}else{fos = new FileOutputStream(new File(targetPath + File.separator + entry.getName()));int count;byte data[] = new byte[2048];while ((count = tis.read(data)) != -1) {fos.write(data, 0, count);}fos.flush();}}} catch (IOException e) {e.printStackTrace();}finally {try {if(fis != null){fis.close();}if(fos != null){fos.close();}if(bis != null){bis.close();}if(tis != null){tis.close();}} catch (IOException e) {e.printStackTrace();}}}

更多java相关,请查看:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。