编译日期和时间 [英] Compile date and time

查看:365
本文介绍了编译日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在与C& C相当的Java? C ++编译时常量__DATE__和__TIME__。我需要打印正在编译的程序的编译时间和版本信息。

Is there a Java equivalent to the C & C++ compile-time constants __DATE__ and __TIME__. I need to print compile time and version info of the program being compiled.

谢谢

kodev19

推荐答案

据我所知,没有类似的东西。
但是在运行的JVM上你可以使用类似下面代码的东西直接从jar获取一些信息(这里,信息来自编译时放在jar中的Manifest文件(无论你的构建系统是什么) ,Ant或Maven或其他任何东西)。随意调整它(不同的输出,等等)。

As far as i know, there is nothing like that. But on a running JVM you can get a few informations straight away from the jar using something like the code below (here, the information comes from the Manifest file put in the jar at compilation time (which ever your build system is, Ant or Maven or anything else). Feel free to adapte it (different output, and so on).

    public String getVersionfinal Class classe) {
    String version = null;
    String shortClassName = classe.getName().substring(classe.getName().lastIndexOf(".") + 1);
    try {
        ClassLoader cl = this.getClass().getClassLoader();
        String threadContexteClass = classe.getName().replace('.', '/');
        URL url = cl.getResource(threadContexteClass + ".class");
        if ( url == null ) {
            version = shortClassName + " $ (no manifest)";
        } else {
            String path = url.getPath();
            String jarExt = ".jar";
            int index = path.indexOf(jarExt);
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            if (index != -1) {
                String jarPath = path.substring(0, index + jarExt.length());
                File file = new File(jarPath);
                String jarVersion = file.getName();
                JarFile jarFile = new JarFile(new File(new URI(jarPath)));
                JarEntry entry = jarFile.getJarEntry("META-INF/MANIFEST.MF");
                version = shortClassName + " $ " + jarVersion.substring(0, jarVersion.length()
                        - jarExt.length()) + " $ "
                        + sdf.format(new Date(entry.getTime()));
                CloseHelper.close(jarFile);
            } else {
                File file = new File(path);
                version = shortClassName + " $ " + sdf.format(new Date(file.lastModified()));
            }
        }
    } catch (Exception e) {
        version = shortClassName + " $ " + e.toString();
    }
    return version;
}

将输出一次使用类似的东西(此处为可用的StringUtils.class commons-lang-2.4.jar于2008年3月15日20:43汇编):

will output once used something like (here for the StringUtils.class available in the commons-lang-2.4.jar compiled on 15 march 2008 20:43) :


StringUtils $ commons-lang-2.4 $ 15/03 / 2008 20:43:16

StringUtils $ commons-lang-2.4 $ 15/03/2008 20:43:16

这篇关于编译日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆