我需要从位于每个 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/