Home > other >  How can I add file version detail on properties to a .jar?
How can I add file version detail on properties to a .jar?

Time:03-11

I'm looking to add a product version number to appear in my .jar file information. Currently I'm using Maven in my Spring boot project for API Rest.

I have read a lot of solutions about the manifest versioning. There you have to decompress and access to the META-INF/MANIFEST.MF to check the Implementation-Version. That's too tedious for what I'm looking for.

Like for a .exe. where you can found it under right mouse click -> details -> "product version" or simply checking on File Version column as shown on image. Example of a file version description.

Also I read that JAR file is a file format based on the popular ZIP file format and is used for aggregating many files into one. Kinda that I'm looking to add a file version to .zip, but I want to ask anyway if that is possible.

Regards, Gaspar.

CodePudding user response:

Just include a text file anywhere in your jar. Build systems of all stripes make this trivial. Then write in your code that you read out this text file with the version, and show it on screen.

In maven, gradle, etc, to include a plain text file in the jar, just put it in src/main/resources/version.txt and it gets included automatically.

To read it in java:

public class Main {
  public static String getVersion() {
    try (var in = Main.class.getResourceAsStream("/version.txt")) {
      return new String(in.readAllBytes(), StandardCharsets.UTF_8);
    }
  }
}

This:

  • Asks the classloader to load version.txt using the same systems that load .class files.
  • reads that inputstream fully, and turns it into a string using the UTF_8 encoding.
  • Uses try-with-resources because, it's a resource, you have to do that if you don't want leaks.

CodePudding user response:

A JAR file itself can't have a version. But you're using Maven, and that means you can already access the Maven version:

try (InputStream inputStream = getClass().getResourceAsStream("/META-INF/maven/<groupId>/<artifactId>/pom.properties")) {
    Properties properties = new Properties();
    properties.load(inputStream);
    // available properties:
    // - artifactId=xxx
    // - groupId=xxx
    // - version=xxx
}

Note that this often doesn't work in unit tests (especially when run from IDEs) because the files are only added to the JAR file.

  • Related