前段项目中有块时需要解压tar.gz文件的需要,我百度了好久,没有合适的。因为我需要解压后直接写入内存进行文件解析,而不是写入本地文件里。后来终于遇到对的人,提供了解决方案,以此记录。
public static void main(String[] args) throws Exception {
File file = new File("D:\\testFolder\\redis.tar.gz");
FileInputStream fis = new FileInputStream(file);
Map<String, byte[]> map = uncompressToByteArray(fis);
FileOutputStream fout = null;
//获取文件名称
for (Map.Entry thisentry : map.entrySet()) {
Object key = thisentry.getKey();
//解析对应的文件内容 元类型是byte[]
byte[] bytes = map.get(key);
//写入文件 此处也可以省略
File file2 = new File("D://testt//cc.txt");
fout = new FileOutputStream(file2);
fout.write(bytes);
//将文件内容解析
String str = new String(bytes,"utf-8");
System.out.println("当前文件:" + key);
System.out.println(str);
fout.close();
}
System.out.println("解压后有"+map.size()+"个文件");
}
public static Map<String, byte[]> uncompressToByteArray(InputStream fis) {
try {
GZIPInputStream is = new GZIPInputStream(new BufferedInputStream(fis));
ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar" , is);
Map<String, byte[]> map = new HashMap<>();
TarArchiveEntry entry = null;
while ( (entry = (TarArchiveEntry)in.getNextEntry() ) != null) {
String name = entry.getName();
if (! entry.isDirectory()) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = -1;
while ((len = in.read(buf, 0, buf.length)) > -1) {
out.write(buf, 0, len);
}
map.put(name, out.toByteArray());
out.close();
}
}
in.close();
return map;
} catch(Exception e) {
throw new RuntimeException(e);
}
}
以上就是完整参考。
工作四个月了,觉得自己欠缺的太多了,还是什么都不会,好多东西都得问,悟性太差啊这老铁,不过,加油~