使用Apache的commons-compress-1.9.jar实现jar压缩和解压tar文件
(1)压缩文件
private static void tarFile(File file, TarArchiveOutputStream taos) throws Exception {
TarArchiveEntry tae = new TarArchiveEntry(file);
tae.setSize(file.length());//大小
tae.setName(new String(file.getName().getBytes("gbk"), "ISO-8859-1"));//不设置会默认全路径
taos.putArchiveEntry(tae);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int count;
byte data[] = new byte[1024];
while ((count = bis.read(data, 0, 1024)) != -1) {
taos.write(data, 0, count);
}
bis.close();
taos.closeArchiveEntry();
}
(2)解压文件
private static void deTarFile(String destPath, TarArchiveInputStream tais) throws Exception {
TarArchiveEntry tae = null;
while ((tae = tais.getNextTarEntry()) != null) {
String dir = destPath + File.separator + tae.getName();//tar档中文件
File dirFile = new File(dir);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dirFile));
int count;
byte data[] = new byte[1024];
while ((count = tais.read(data, 0, 1024)) != -1) {
bos.write(data, 0, count);
}
bos.close();
}
}
测试
//压缩
try {
TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(new File("/Users/enderwang/Downloads/testTar/test.tar")));
archiveFile(new File("/Users/enderwang/Downloads/1.txt"), taos);
archiveFile(new File("/Users/enderwang/Downloads/2.txt"), taos);
System.out.println("压缩成功");
} catch (Exception ex) {
ex.printStackTrace();
}
//解压
try {
TarArchiveInputStream tais = new TarArchiveInputStream(new FileInputStream(new File("/Users/enderwang/Downloads/testTar/test.tar")));
dearchive("/Users/enderwang/Downloads/testTar", tais);
tais.close();
System.out.println("解压成功");
} catch (Exception ex) {
ex.printStackTrace();
}
本文介绍如何利用Apache的commons-compress-1.9.jar库进行tar文件的压缩与解压操作。提供了具体的Java代码示例,包括创建tar归档文件以及从tar文件中提取内容。
7081

被折叠的 条评论
为什么被折叠?



