【问题标题】:How to read a file in Groovy into a string, without knowing the path to the file?如何在不知道文件路径的情况下将 Groovy 中的文件读入字符串?
【发布时间】:2017-06-09 10:10:38
【问题描述】:

扩展至this question

是否可以在不知道文件路径的情况下将文件读入字符串? - 我只有文件作为“def”/无类型参数,这就是为什么我不能只做一个 .getAbsolutePath()

详细说明,这是我导入文件的方式(来自临时 .jar 文件)

def getExportInfo(path) {
  def zipFile = new java.util.zip.ZipFile(new File(path))

  zipFile.entries().each { entry ->
    def name = entry.name
    if (!entry.directory && name == "ExportInfo") {
      return entry
    }
  }
}

【问题讨论】:

  • “文件”是什么意思?它是您在那个无类型参数中拥有的File 对象,那么它是相同的。 Groovy 是鸭子类型的,所以如果它是 File 对象,您可以将其用作 File 对象,即使变量类型未定义。你到底有什么?
  • @Vampire 不,它不是文件对象,编辑解释
  • @JonasPraem,type-less parameter 是什么?为什么你把你的问题 zip 文件 reding?你能解释一下你需要什么吗?
  • 所以你想看entry的内容还是什么?
  • @Vampire 是的,我看过条目的内容

标签: string file groovy io


【解决方案1】:

ZipEntry 不是文件,而是ZipEntry

这些几乎没有共同点。

使用def is = zipFile.getInputStream(entry),您可以获得zip 条目内容的输入流。

然后您可以使用is.text 获取默认平台编码中String 的内容,或者使用is.getText('<theFilesEncoding>') 获取指定编码中String 的内容,与使用@ 完全相同987654328@对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多