您的位置:首页 > 其它

zip,jar,tar.gz无需解压读取文件内容

2015-12-09 17:55 1476 查看

1。zip包读取

/**
* 读取zip中version.json的数据
* */
public String readZipFile(String file) throws Exception {
StringBuffer sb = new StringBuffer();
ZipFile zf = new ZipFile(file);
InputStream in = new BufferedInputStream(new FileInputStream(file));
ZipInputStream zin = new ZipInputStream(in);
ZipEntry ze;
while ((ze = zin.getNextEntry()) != null) {
//如果是文件夹
if (ze.isDirectory()) {
} else {
if(ze.getName().equals("installer/config/version.json")){
long size = ze.getSize();
if (size > 0) {
BufferedReader br = new BufferedReader(new InputStreamReader(zf.getInputStream(ze),"utf-8"));
String line;
//读取文件中的内容
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
}
break;

}

}
}
zin.closeEntry();
return sb.toString();
}


2.jar读取文件

public String readFileFromJar(String jarPath ) throws IOException {
JarFile jf = new JarFile(jarPath);
Enumeration<JarEntry> jfs = jf.entries();
StringBuffer sb  = new StringBuffer();
while(jfs.hasMoreElements())
{
JarEntry jfn = jfs.nextElement();
if(jfn.getName().endsWith("/version.json"))
{
InputStream is = jf.getInputStream(jfn);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buf = new byte[is.available()];
while(bis.read(buf)!=-1)
{
sb.append(new String(buf).trim());
}
bis.close();
is.close();
break;
}
}
return sb.toString();
}

3.tar.gz读取文件,需要添加一个jar包
org.apache.commons.compress

public String readTarGz(String tarPath) throws IOException {
File targzFile = new File(tarPath);
FileInputStream fileIn = null;
BufferedInputStream bufIn = null;
GZIPInputStream gzipIn = null;
TarArchiveInputStream taris = null;
try {
fileIn = new FileInputStream(targzFile);
bufIn = new BufferedInputStream(fileIn);
gzipIn = new GZIPInputStream(bufIn);
taris = new TarArchiveInputStream(gzipIn);
TarArchiveEntry entry = null;
while ((entry = taris.getNextTarEntry()) != null) {
if (entry.isDirectory())
continue;
System.out.println(entry.getName());
if(entry.getName().equals("config/version.json")){
byte[] b = new byte[(int) entry.getSize()];
taris.read(b, 0, (int) entry.getSize());
return new String(b);
}
}
} finally {
taris.close();
gzipIn.close();
bufIn.close();
fileIn.close();
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: