有用javajava 解压缩tar.gz过.gz包的没,求助

在 SegmentFault,学习技能、解决问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。
问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
1.需求是有一个外部接口返回的比较长的字符串,将这个字符串在应用某个目录下存储为压缩文件,也就是将字符串压缩存放。
提供一个解压缩获取原始串的方法供查询。
问题,现在使用gz压缩后压缩效果不理想,原本500KB的串,压缩后大小是原串的一半,还能再压小些吗?
还需要考虑解压缩的效率,耗时不要太长。
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
public static byte[] compress(String str) {
if (str == null || str.length() == 0) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputS
gzip = new GZIPOutputStream(out);
//gzip = new GZIPOutputStream(out){{def.setLevel(Deflater.BEST_COMPRESSION);}}; //效果同上
gzip.write(str.getBytes("UTF-8"));
gzip.close();
} catch (IOException e) {
System.out.println("gzip compress error." + e);
return out.toByteArray();
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
创建GzipOutputStream的时候,set一下compression rate: OutputStream gzipout = new GZIPOutputStream(bos){{def.setLevel(Deflater.BEST_COMPRESSION);}};
即使默认情况下,字符串也可以压缩很多,只压缩一半不正常。
同步到新浪微博
分享到微博?
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:
在 SegmentFault,学习技能、解决问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。java解压缩.gz、.z类型的压缩文件? - ITeye问答
需要将拿到的 gz、z格式的压缩文件解压缩后做处理。通过java代码怎么实现?或者有什么开源工具包可用?gz、z压缩包里含有多个文件。
问题补充:对java内置的Api 只有gzip的。好像只能对包含了一个文件的gzip包解压。对.z没找到对应的Api
问题补充:在window环境下
采纳的答案
使用 [url=" http://commons.apache.org/compress/index.html"]Apache Commons Compress[/url]
用什麽格式壓縮的啊。
.gz .z是你看到的文件擴展名吧。還是我孤陋寡聞了。
java只能解壓zip(jar也是)
rar可調用命令去解壓
java内置解压方法。你查一下 jdk 文档就好了
已解决问题
未解决问题博客分类:
发送请求(要求服务端对response进行GZip压缩):
import org.apache.commons.httpclient.HttpC
import org.apache.commons.httpclient.HttpS
public class TestGzip {
private final static String url = "http://localhost:8888/ltest.jsp";
public static void main(String[] args) throws Exception{
HttpClient http = new HttpClient();
CustomGetMethod get = new CustomGetMethod(url);
//添加头信息告诉服务端可以对Response进行GZip压缩
get.setRequestHeader("Accept-Encoding", "gzip, deflate");
int statusCode = http.executeMethod(get);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "
+ get.getStatusLine());
//打印解压后的返回信息
System.out.println(get.getResponseBodyAsString());
} catch (Exception e) {
System.err.println("页面无法访问");
e.printStackTrace();
} finally {
get.releaseConnection();
下面是CustomGetMethod.java的内容,getResponseBodyAsString()方法被重写,加入了解压功能
import java.io.IOE
import java.io.InputS
import java.io.InputStreamR
import java.util.zip.GZIPInputS
public class CustomGetMethod extends org.apache.commons.httpclient.methods.GetMethod{
public CustomGetMethod(String uri) {
super(uri);
* Get response as string whether response is GZipped or not
* @throws IOException
public String getResponseBodyAsString() throws IOException {
GZIPInputS
if (getResponseBody() != null || getResponseStream() != null) {
if(getResponseHeader("Content-Encoding") != null
&& getResponseHeader("Content-Encoding").getValue().toLowerCase().indexOf("gzip") & -1) {
//For GZip response
InputStream is = getResponseBodyAsStream();
gzin = new GZIPInputStream(is);
InputStreamReader isr = new InputStreamReader(gzin, getResponseCharSet());
java.io.BufferedReader br = new java.io.BufferedReader(isr);
StringBuffer sb = new StringBuffer();
while ((tempbf = br.readLine()) != null) {
sb.append(tempbf);
sb.append("\r\n");
isr.close();
gzin.close();
return sb.toString();
//For deflate response
return super.getResponseBodyAsString();
浏览 29760
&&& public String getResponseBodyAsString(HttpEntity entity ) throws IOException {& &&&&&&& GZIPInputStream gzin =& &&&&&&& &&&&&&&&&&&&& &&&&&&&&&&& &&&&&&&&&&&&&&&&&&& //For GZip response& &&&&&&&&&&&&&&&&&&& InputStream is = entity.getContent();&&&&&&&&&&&&&&&&&&& gzin = new GZIPInputStream(is);& &&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&& //InputStreamReader isr = new InputStreamReader(gzin, "utf8");&& &&&&&&&&&&&&&&&&&&& //java.io.BufferedReader br = new java.io.BufferedReader(isr);&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&& StringBuffer sb = new StringBuffer();& &&&&&&&&&&&&&&&&&&& List&byte[]& arr =new ArrayList&byte[]&();&&&&&&&&&&&&&&&&&&& try {&&&&&&&&&&&&&&&&&&& byte[] by= new byte[1024];&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&& int actlength=0;&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&& while((actlength=gzin.read(by))!=-1){&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&& byte[] b=Arrays.copyOf(by, actlength);;&&&&&&&&&&&&&&&&&&&&&&& arr.add(b);&&&&&&&&&&&&&&&&&&&&&& // String s= new String(b,"utf8");&&&&&&&&&&&&&&&&&&&& //&& System.out.print(s);&&&&&&&&&&&&&&&&&&&& //&& System.out.println("@@@@@@@@@");&&&&&&&&&&&&&&&&&&&& //&& sb.append(s);&&&&&&&&&&&&&&&&&&&& //&& actlength = 0;&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&&&&& //&&&&&&&&&&&&&&&&&&& //&&&&&&&&&&&&&&&&&&& StringBuffer sb = new StringBuffer();& //&&&&&&&&&&&&&&&&&&& S& &&&&&&&&&&&&&&&&&& //&&&&&&&&&&&&&&&&&&&&&&& while ((tempbf = br.readLine()) != null) {& //&&&&&&&&&&&&&&&&&&&&&&&&&&& sb.append(tempbf);& //&&&&&&&&&&&&&&&&&&&&&&&&&&& sb.append("\r\n");& //&&&&&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&&&&& catch (java.io.EOFException e) {&&&&&&&&&&&&&&&&&&&&&&& // TODO Auto-generated catch block&&&&&&&&&&&&&&&&&& //&&&& e.printStackTrace();&&&&&&&&&&&&&&&&&&&&&&& int actlength=0;&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&& //&& List&byte[]& arr =new ArrayList&byte[]&();&&&&&&&&&&&&&&&&&&&&&&& actlength = 0;&&&&&&&&&&&&&&&&&&&&&&& for(byte[] b : arr){&&&&&&&&&&&&&&&&&&&&&&&&&&& actlength+=b.&&&&&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&&&&&&&&& byte[] by1= new byte[actlength];&&&&&&&&&&&&&&&&&&&&&&& actlength = 0;&&&&&&&&&&&&&&&&&&&&&&& for(byte[] b : arr){&&&&&&&&&&&&&&&&&&&&&&&&&&& System.arraycopy(b,0,by1,actlength,b.length);&&&&&&&&&&&&&&&&&&&&&&&&&&& actlength+=b.&&&&&&&&&&&&&&&&&&&&&&&&&&& //Arrays.&&&&&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&&&&&&&&& String s= new String(by1,"utf8");&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&& sb.append(s);&&&&&&&&&&&&&&&&&&& }& //&&&&&&&&&&&&&&&&&&& isr.close();& //&&&&&&&&&&&&&&&&&&& gzin.close();& &&&&&&&&&&&&&&&&&&& return sb.toString();&&&&&&&&&&&&&&&& //&& return "";&&&&&&&&&&&&&&& &&&&&&&&&&&&&&& //For deflate response& &&&&&&&&&&&& &&&&&&&& & &&& }& 这样就ok了,可以处理中文
javajava22 写道截取部分代码 ,抛错
java.io.EOFException
at java.util.zip.GZIPInputStream.readUByte(GZIPInputStream.java:207)
at java.util.zip.GZIPInputStream.readUShort(GZIPInputStream.java:197)
at java.util.zip.GZIPInputStream.readUInt(GZIPInputStream.java:189)
at java.util.zip.GZIPInputStream.readTrailer(GZIPInputStream.java:179)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:94)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
你是在linux or windows?
windows , 发现这个和普通的IO 好像 有区别,换成 读取byte 后一样报错,不过捕捉就行了,内容还是没错,不过让人抓狂的是 抓取解压的代码 有时候是中文,有时候部分是乱码,呵呵
截取部分代码 ,抛错java.io.EOFException at java.util.zip.GZIPInputStream.readUByte(GZIPInputStream.java:207) at java.util.zip.GZIPInputStream.readUShort(GZIPInputStream.java:197) at java.util.zip.GZIPInputStream.readUInt(GZIPInputStream.java:189) at java.util.zip.GZIPInputStream.readTrailer(GZIPInputStream.java:179) at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:94) at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264) at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158) at java.io.InputStreamReader.read(InputStreamReader.java:167) at java.io.BufferedReader.fill(BufferedReader.java:136) at java.io.BufferedReader.readLine(BufferedReader.java:299) at java.io.BufferedReader.readLine(BufferedReader.java:362)你是在linux or windows?
zhoulei984623
浏览: 382618 次
来自: 苏州
工作了好多年,今天刚好用到它。
有一个外部引用谷歌api没办法download
这里写错了应该。。。--sm-plugins=......,+ ...
spring的 threadpool
没有submit方法呀 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'java把多个文件打成zip压缩包
import java.io.*;
import org.apache.tools.zip.ZipOutputS
import org.apache.tools.zip.ZipE
public class demo1 {
&&&&public
static void main( String[] args ) {
&&&&&&&&try
String[] strs = new String[5];
strs[0]="D:/workspace_myeclipse/GZRAIL/src/www/resource/word/lessonmanager/doc1/钟如燕.doc";
strs[1]="D:/workspace_myeclipse/GZRAIL/src/www/resource/word/lessonmanager/doc1/马蓉.doc";
strs[2]="D:/workspace_myeclipse/GZRAIL/src/www/resource/word/lessonmanager/doc1/邹青宜.doc";
strs[3]="D:/workspace_myeclipse/GZRAIL/src/www/resource/word/lessonmanager/doc1/周黎.doc";
strs[4]="D:/workspace_myeclipse/GZRAIL/src/www/resource/word/lessonmanager/doc1/邝莉莉.doc";
//文件的列表 和 将要打成的zip文件的名称
&&&&&&&&&&&&writeZip(strs,"123456");
catch ( IOException e ) {
&&&&&&&&&&&&e.printStackTrace();
&&&&private
static void writeZip(String[] strs,String zipname) throws
IOException {
&&&&&&&&String[]
&&&&&&&&OutputStream
os = new BufferedOutputStream( new FileOutputStream(
"D:/workspace_myeclipse/GZRAIL/src/www/resource/word/lessonmanager/doc1/"+zipname+".zip"
&&&&&&&&ZipOutputStream
zos = new ZipOutputStream( os );
&&&&&&&&byte[]
buf = new byte[8192];
&&&&&&&&int
&&&&&&&&for
(int i=0;i&files.i++)
&&&&&&&&&&&&File
file = new File( files );
&&&&&&&&&&&&if
( !file.isFile() )
&&&&&&&&&&&&ZipEntry
ze = new ZipEntry( file.getName() );
&&&&&&&&&&&&zos.putNextEntry(
&&&&&&&&&&&&BufferedInputStream
bis = new BufferedInputStream( new FileInputStream( file ) );
&&&&&&&&&&&&while
( ( len = bis.read( buf ) ) & 0 ) {
&&&&&&&&&&&&&&&&zos.write(
buf, 0, len );
&&&&&&&&&&&&}
&&&&&&&&&&&&zos.closeEntry();
&&&&&&&&zos.setEncoding("GBK");
&&&&&&&&zos.closeEntry();
&&&&&&&&zos.close();
&&&&&&&&for(int
i=0;i&files.i++){
System.out.println("------------"+files );
File file= new File(files );
file.delete();
ant jar包下载地址:
我的更多文章:
( 08:35:32)( 09:49:36)( 20:56:10)( 11:28:57)( 12:18:20)( 10:06:19)( 09:53:38)( 09:44:02)( 14:22:46)( 21:09:46)
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。博客分类:
import java.io.BufferedInputS
import java.io.BufferedOutputS
import java.io.F
import java.io.FileInputS
import java.io.FileOutputS
import java.io.IOE
import java.util.ArrayL
import java.util.L
import java.util.zip.GZIPInputS
import java.util.zip.ZipE
import java.util.zip.ZipInputS
import org.apache.commons.compress.archivers.ArchiveInputS
import org.apache.commons.compress.archivers.ArchiveStreamF
import org.apache.commons.compress.archivers.tar.TarArchiveE
import org.apache.commons.logging.L
import org.apache.commons.logging.LogF
public class GZip
// 日志对象
private static Log logger = LogFactory.getLog(GZip.class);
* &解压tar包&
* &该方法只适用于解压tar包&
* @param rarFileName 需要解压的文件路径(具体到文件)
* @param destDir 解压目标路径
* @return 执行结果
* @see [类、类#方法、类#成员]
public static boolean unTargzFile(String rarFileName, String destDir, List&String& fileNames)
if (!Global.isEmpty(rarFileName) && !Global.isEmpty(destDir))
Global.mkdirs(destDir);
return unGzipFile(rarFileName, destDir, fileNames);
catch (Exception e)
logger.error(Global.LOG_EXCEPTION_NAME, e);
* &解压zip包&
* &该方法只适用于解压zip包&
* @param rarFileName 需要解压的文件路径(具体到文件)
* @param destDir 解压目标路径
* @return 执行结果
* @see [类、类#方法、类#成员]
public static void unZipFile(String rarFileName, String destDir, List&String& fileNames)
if (!Global.isEmpty(rarFileName) && !Global.isEmpty(destDir))
Global.mkdirs(destDir);
ReadZip(rarFileName, destDir, fileNames);
catch (Exception e)
logger.error(Global.LOG_EXCEPTION_NAME, e);
* &解压缩文件&
* &解压标准gzip格式的压缩包&
* @param zipfileName 需要解压的文件路径(具体到文件)
* @param outputDirectory 解压目标路径
* @see [类、类#方法、类#成员]
private static boolean unGzipFile(String zipfileName, String outputDirectory, List&String& fileNames)
FileInputStream fis =
ArchiveInputStream in =
BufferedInputStream bis =
fis = new FileInputStream(zipfileName);
GZIPInputStream gis = new GZIPInputStream(new BufferedInputStream(fis));
in = new ArchiveStreamFactory().createArchiveInputStream("tar", gis);
bis = new BufferedInputStream(in);
TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry();
while (entry != null)
String name = entry.getName();
String[] names = name.split("/");
String fileName = outputD
for (int i = 0; i & names. i++)
String str = names[i];
fileName = fileName + File.separator +
if (name.endsWith("/"))
Global.mkdirs(fileName);
File file = getRealFileName(outputDirectory, name);
if (null != fileNames)
fileNames.add(file.getName());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
int b = -1;
while ((b = bis.read()) != -1)
bos.write(b);
bos.flush();
bos.close();
entry = (TarArchiveEntry)in.getNextEntry();
catch (Exception e)
logger.error(Global.LOG_EXCEPTION_NAME, e);
if (null != bis)
bis.close();
catch (IOException e)
logger.error(Global.LOG_EXCEPTION_NAME, e);
* &解压缩zip包&
* &功能详细描述&
* @param unzipPath
* @param zippath
* @see [类、类#方法、类#成员]
public static void ReadZip(String unzipPath, String zippath, List&String& fileNames)
BufferedOutputStream dest =
FileInputStream fis = new FileInputStream(unzipPath);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry =
while ((entry = zis.getNextEntry()) != null)
String name = entry.getName();
String[] names = name.split("/");
String fileName =
for (int i = 0; i & names. i++)
String str = names[i];
fileName = fileName + File.separator +
if (name.endsWith("/"))
Global.mkdirs(fileName);
byte data[] = new byte[2048];
File file = getRealFileName(zippath, name);
if (null != fileNames)
fileNames.add(file.getName());
dest = new BufferedOutputStream(new FileOutputStream(file));
while ((count = zis.read(data, 0, 2048)) != -1)
dest.write(data, 0, count);
dest.flush();
dest.close();
zis.close();
catch (Exception e)
logger.error(Global.LOG_EXCEPTION_NAME, e);
* 给定根目录,返回一个相对路径所对应的实际文件对象
* @param zippath 指定根目录
* @param absFileName 相对路径名,来自于ZipEntry中的name
* @return File 实际的文件
private static File getRealFileName(String zippath, String absFileName)
String[] dirs = absFileName.split("/", absFileName.length());
File ret = new File(zippath);// 创建文件对象
if (dirs.length & 1)
for (int i = 0; i & dirs.length - 1; i++)
ret = new File(ret, dirs[i]);
if (!ret.exists())
// 检测文件是否存在
ret.mkdirs();// 创建此抽象路径名指定的目录
// 根据 ret 抽象路径名和 child 路径名字符串创建一个新 File 实例
ret = new File(ret, dirs[dirs.length - 1]);
public static void main(String[] args)
List&String& unzipOne = new ArrayList&String&();
List&String& unzipTwo = new ArrayList&String&();
GZip.unTargzFile("F:/fap.8.tar.gz", "F:/111", unzipOne);
int size = unzipOne.size();
for (int i = 0; i & i++)
GZip.unTargzFile("F:/111/" + unzipOne.get(i), "F:/222", unzipTwo);
亲,你这Global类能给一份么
lengchaotian
浏览: 214614 次
来自: 西安
czb6788782 写道亲,你这Global类能给一份么
[size=small][/size]u;8i
定时任务在启动的时候可以传参数么?
亲,你这Global类能给一份么
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'

我要回帖

更多关于 java 解压缩tar.gz 的文章

 

随机推荐