java 解压文件需要什么jar_Java解压Jar文件

今天写点java解压jar文件的东西,以前项目中用到过,很简单。。。

java中有专门的文件类型对应jar文件,那就是JarFile,用于从任何可以使用java.io.RandomAccessFile打开的文件中读取jar文件内容,详情可参考JarFile

解压只是使用JarFile的相关api,源码如下:

public class JARDecompressionTool {

/**

* 解压并删除jar文件

*/

public static synchronized void decompress(String fileName,String outputPath){

if (!outputPath.endsWith(File.separator)) {

outputPath += File.separator;

}

File dir = new File(outputPath);

if (!dir.exists()) {

dir.mkdirs();

}

JarFile jf = null;

try{

jf = new JarFile(fileName);

for (Enumeration e = jf.entries(); e.hasMoreElements();) {

JarEntry je = (JarEntry) e.nextElement();

String outFileName = outputPath + je.getName();

File f = new File(outFileName);

if(je.isDirectory()){

if(!f.exists()){

f.mkdirs();

}

}else{

File pf = f.getParentFile();

if(!pf.exists()){

pf.mkdirs();

}

InputStream in = jf.getInputStream(je);

OutputStream out = new BufferedOutputStream(

new FileOutputStream(f));

byte[] buffer = new byte[2048];

int nBytes = 0;

while ((nBytes = in.read(buffer)) > 0) {

out.write(buffer, 0, nBytes);

}

out.flush();

out.close();

in.close();

}

}

}catch(Exception e){

System.out.println("解压"+fileName+"出错---"+e.getMessage());

}finally{

if(jf!=null){

try {

jf.close();

File jar = new File(jf.getName());

if(jar.exists()){

jar.delete();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值