栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Java(JSP)中提取.tar.gz文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Java(JSP)中提取.tar.gz文件

好的,我终于弄清楚了,这是我的代码,以防将来对任何人有帮助。它是用Java使用apache commons io和compress库编写的。

File dir = new File("directory/of/.tar.gz/files/here");File listDir[] = dir.listFiles();if (listDir.length!=0){    for (File i:listDir){                if (i.isDirectory()){ break;        }        String fileName = i.toString();        String tarFileName = fileName +".tar";        FileInputStream instream= new FileInputStream(fileName);        GZIPInputStream ginstream =new GZIPInputStream(instream);        FileOutputStream outstream = new FileOutputStream(tarFileName);        byte[] buf = new byte[1024];         int len;        while ((len = ginstream.read(buf)) > 0)         { outstream.write(buf, 0, len);        }        ginstream.close();        outstream.close();        //There should now be tar files in the directory        //extract specific files from tar        TarArchiveInputStream myTarFile=new TarArchiveInputStream(new FileInputStream(tarFileName));        TarArchiveEntry entry = null;        int offset;        FileOutputStream outputFile=null;        //read every single entry in TAR file        while ((entry = myTarFile.getNextTarEntry()) != null) { //the following two lines remove the .tar.gz extension for the folder name String fileName = i.getName().substring(0, i.getName().lastIndexOf('.')); fileName = fileName.substring(0, fileName.lastIndexOf('.')); File outputDir =  new File(i.getParent() + "/" + fileName + "/" + entry.getName()); if(! outputDir.getParentFile().exists()){      outputDir.getParentFile().mkdirs(); } //if the entry in the tar is a directory, it needs to be created, only files can be extracted if(entry.isDirectory){     outputDir.mkdirs(); }else{     byte[] content = new byte[(int) entry.getSize()];     offset=0;     myTarFile.read(content, offset, content.length - offset);     outputFile=new FileOutputStream(outputDir);     IOUtils.write(content,outputFile);       outputFile.close(); }        }        //close and delete the tar files, leaving the original .tar.gz and the extracted folders        myTarFile.close();        File tarFile =  new File(tarFileName);        tarFile.delete();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/633478.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号