groovy – 修改zipfile条目的文件内容
发布时间:2020-12-14 16:20:52 所属栏目:大数据 来源:网络整理
导读:我想更新位于zipfile内的文本文件的内容. 我无法找到如何执行此操作,以下代码无法正常工作. 谢谢你的帮助!! import java.util.zip.ZipFileimport java.util.zip.ZipEntryimport java.util.zip.ZipOutputStreamString zipFileFullPath = "C:/path/to/myzipfil
我想更新位于zipfile内的文本文件的内容.
我无法找到如何执行此操作,以下代码无法正常工作. 谢谢你的帮助!! import java.util.zip.ZipFile import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream String zipFileFullPath = "C:/path/to/myzipfile/test.zip" ZipFile zipFile = new ZipFile(zipFileFullPath) ZipEntry entry = zipFile.getEntry ( "someFile.txt" ) if(entry){ InputStream input = zipFile.getInputStream(entry) BufferedReader br = new BufferedReader(new InputStreamReader(input,"UTF-8")) String s = null StringBuffer sb = new StringBuffer() while ((s=br.readLine())!=null){ sb.append(s) } sb.append("adding some text..") ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileFullPath)) out.putNextEntry(new ZipEntry("someFile.txt")); int length InputStream fin = new ByteArrayInputStream(sb.toString().getBytes("UTF8")) while((length = fin.read(sb)) > 0) { out.write(sb,length) } out.closeEntry() } 解决方法
只是对@Opal的答案进行了一些细微的修改,我只是:
>尽可能使用groovy方法 Groovy Snippet void updateZipEntry(String zipFile,String zipEntry,String newContent){ def zin = new ZipFile(zipFile) def tmp = File.createTempFile("temp_${System.nanoTime()}",'.zip') tmp.withOutputStream { os -> def zos = new ZipOutputStream(os) zin.entries().each { entry -> def isReplaced = entry.name == zipEntry zos.putNextEntry(isReplaced ? new ZipEntry(zipEntry) : entry) zos << (isReplaced ? newContent.getBytes('UTF8') : zin.getInputStream(entry).bytes ) zos.closeEntry() } zos.close() } zin.close() assert new File(zipFile).delete() tmp.renameTo(zipFile) } 用法 updateZipEntry('/tmp/file.zip','META-INF/web.xml','<foobar>new content!</foobar>') (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- thinkphp模板中,checkbox回显问题
- 求助改善Delphi调用olevariant出现“被呼叫方拒绝接收呼叫”
- golang 创建一个简单的资源池,重用资源,减少GC负担
- groovy – 使用脚本有条件地更新Elasticsearch中的文档
- 大数加法(C语言)#include<stdio.h> #include<std
- 发现Delphi.XE2.Update3 上使用 FireMonkey 开发,对 TImag
- 用Delphi开发视频聊天软件
- 解释Perl代码以KB,MB,GB等显示多个字节
- golang设计模式之建造者模式
- clientDataSet和TDataSetProvider对数据的操作