java - 从 jar 中的属性文件读取特定属性

标签 java zip properties-file

我需要从位于每个 jar 的根级别的属性文件“version.properties”中读取属性“product.build.number”。我天真的做法是:

  private static int getProductBuildNumber(File artefactFile) throws FileNotFoundException, IOException
  {
    try (ZipInputStream zip = new ZipInputStream(new FileInputStream(
        artefactFile)))
    {

      Set<String> possClasses = new HashSet<>();

      for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip
          .getNextEntry())
      {
        if (!entry.isDirectory() && entry.getName().toLowerCase().equals(
            "version.properties"))
        {
          List<String> lines = IOUtils.readLines(zip, (String) null);

          for (String line : lines)
          {
            if (line.startsWith("product.build.number"))
            {
              String[] split = line.split("=");
              if (split.length == 2)
              {
                return Integer.parseInt(split[1]);
              }

            }
          }

        }
      }
    }

    throw new IOException("product.build.number not found.");

  }

我想还有更优雅、更可靠的方法。有什么想法吗?

最佳答案

尝试类似的东西(未经测试):

private static int getProductBuildNumber(Path artefactFilePath) throws IOException{
   try(FileSystem zipFileSystem = FileSystems.newFileSystem(artefactFilePath, null)){
      Path versionPropertiesPath = zipFileSystem.getPath("/version.properties");
      Properties versionProperties = new Properties();
      try (InputStream is = Files.newInputStream(versionPropertiesPath)){
          versionProperties.load(is);
      }
      return Integer.parseInt(versionProperties.getProperty("product.build.number"));
   }
}

关于java - 从 jar 中的属性文件读取特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39275721/

相关文章:

java - Java中的动态数据库连接

java - 从行中分割 ("[\t ]") 是什么意思

java - 在准备好的 stament db2 中设置数组不工作 Java

Android 应用程序在提取 zip 文件时没有响应

testing - 从 maven zip 程序集运行测试

Java ByteArrayOutputStream 到不同的容器中

java - 在 Spring-Boot 4 中,尝试注入(inject)属性文件值

java - 空指针异常 : Attempt to read from field 'int android.app.Fragment.mContainerId' on a null object reference

java - AWS s3图像放置对象

java - Eclipse 错误的 Java 属性 UTF-8 编码