Страницы

Поиск по вопросам

четверг, 13 февраля 2020 г.

Как задать в переменную текущую дату и время при компиляции?

#java #компиляция


В качестве билда программы использую текущую дату и время в специфичном формате на
момент компиляции.

private final String VERSION_REVISION= "20160216_1708";


Как задать переменную что бы при компиляции можно было вставить туда текущую дату
и время. 
    


Ответы

Ответ 1



Пример кода, если использовать File().lastModified(): private final String VERSION_REVISION = getClassBuildTime(); private static Date getClassBuildTime() { Date d = null; Class currentClass = new Object(){}.getClass().getEnclosingClass(); URL resource = currentClass.getResource(currentClass.getSimpleName() + ".class"); if (resource != null) { if (resource.getProtocol().equals("file")) { try { d = new Date(new File(resource.toURI()).lastModified()); } catch (URISyntaxException ignored) { } } else if (resource.getProtocol().equals("jar")) { String path = resource.getPath(); d = new Date( new File(path.substring(5, path.indexOf("!"))).lastModified()); } else if (resource.getProtocol().equals("zip")) { String path = resource.getPath(); File jarFileOnDisk = new File(path.substring(0, path.indexOf("!"))); try (JarFile jf = new JarFile (jarFileOnDisk)) { ZipEntry ze = jf.getEntry (path.substring(path.indexOf("!") + 2)); long zeTimeLong = ze.getTime (); Date zeTimeDate = new Date(zeTimeLong); d = zeTimeDate; } catch (IOException|RuntimeException ignored) { } } } return d; } Как я уже говорил, можете ещё попробовать записать в манифест атрибут Build-Date, а потом считать его: public void readManifest() throws IOException { URL res = getClass().getResource(getClass().getSimpleName() + ".class"); JarURLConnection conn = (JarURLConnection) res.openConnection(); Manifest mf = conn.getManifest(); Attributes atts = mf.getMainAttributes(); System.out.println(atts.getValue("Build-Date")); } Источник кода

Ответ 2



Простой пример с использованием Maven. На тот случай, если не строго обязательно зашивать версию в class файле. Версия задается на этапе сборки, и хранится в property внутри JAR. Проект ├───src │ ├───main │ │ ├───java │ │ │ └───prop │ │ │ Main.java │ │ └───resources │ │ application.properties application.properties version = ${version} pom.xml ${maven.build.timestamp} yyyy-MM-dd HH:mm src/main/resources true // .. Код public static void main(String[] args) { try ( final InputStream stream = Main.class.getClassLoader().getResourceAsStream("application.properties") ) { final Properties properties = new Properties(); properties.load(stream); System.out.println(properties.getProperty("version")); } catch (IOException e) { e.printStackTrace(); } }

Комментариев нет:

Отправить комментарий