package com.xwolf.stat.util; import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream; /**
* tar.gz解压
* @author xwolf
* @date 2016-11-07 15:06
* @since V1.0.0
*/
@Slf4j
public class TarUtil { public static final String ENCODING="GBK";
/**
* 解压缩tar
* @param file
*/
public static String unTarFile(String file) {
List<Map<String,Object>> lists= Lists.newArrayList();
try (FileInputStream fis = new FileInputStream(new File(file));
GZIPInputStream is = new GZIPInputStream(new BufferedInputStream(
fis));
ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is);
InputStreamReader inr = new InputStreamReader(
is,ENCODING);//考虑到编码格式
BufferedReader reader=new BufferedReader(inr)
){
TarArchiveEntry entry = (TarArchiveEntry) in.getNextEntry();
String lineTxt=null;
while (entry != null) {
String name = entry.getName();
String[] nameSplit=name.split("_");
String sn=nameSplit[1];
log.info("name:{},sn:{}",name,sn);
while((lineTxt = reader.readLine()) != null){
String[] keys= lineTxt.split("\t");
Map<String,Object> map = Maps.newHashMap();
map.put("sn",sn);
for(String key:keys){
String[] values =key.split("=");
if(!StringUtils.isEmpty(values[0])){
map.put(values[0],values[1]);
}
}
lists.add(map);
}
entry = (TarArchiveEntry) in.getNextEntry();
}
return JSON.toJSONString(lists);
} catch (Exception e) {
log.error(e.getMessage(),e);
return "";
}
}
}
具体的内容读取可忽略,加上了自己的业务需要。
需要的解压缩依赖