groovy - 修改 zip 文件条目的文件内容

标签 groovy zip

我想更新位于 zip 文件内的文本文件的内容。

我不知道如何执行此操作,并且下面的代码无法正常工作。

感谢您的帮助!!

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, 0, length)
     }             

     out.closeEntry()

}

最佳答案

只是对@Opal的答案进行了一些细微的修改,我只是:

  • 尽可能使用常规方法
  • 封装在方法中

精彩片段

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>')

关于groovy - 修改 zip 文件条目的文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26191893/

相关文章:

regex - 常规正则表达式测试失败

gradle - Groovy 中的测试类在 Kotlin 中看不到测试类

python - 如何创建加密的 ZIP 文件?

Android:从 URL 下载返回的 Zip 文件

powershell - 检查 Zip 文件是否受密码保护

java - 没有tomcat或任何其他servlet容器的Groovy Grails独立应用程序

java - 无法运行路径设置为 Java 6 的 Grails 2.1

string - Groovy 说我的 Unicode 字符串太长

php - 批量压缩 (Zip) 文件

Java文件一个进度条