How do you create a MANIFEST.MF that's available when you're testing and running from a jar in production?

前端 未结 9 998
失恋的感觉
失恋的感觉 2020-12-28 16:28

I\'ve spent far too much time trying to figure this out. This should be the simplest thing and everyone who distributes Java applications in jars must have to deal with it.

9条回答
  •  时光说笑
    2020-12-28 17:22

    Here's what I've found that works:

    packageVersion.java:

    package com.company.division.project.packageversion;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.jar.Attributes;
    import java.util.jar.Manifest;
    
    public class packageVersion
    {
        void printVersion()
        {
            try
            {         
                InputStream stream = getClass().getResourceAsStream("/META-INF/MANIFEST.MF");
    
                if (stream == null)
                {
                    System.out.println("Couldn't find manifest.");
                    System.exit(0);
                }
    
                Manifest manifest = new Manifest(stream);
    
                Attributes attributes = manifest.getMainAttributes();
    
                String impTitle = attributes.getValue("Implementation-Title");
                String impVersion = attributes.getValue("Implementation-Version");
                String impBuildDate = attributes.getValue("Built-Date");
                String impBuiltBy = attributes.getValue("Built-By");
    
                if (impTitle != null)
                {
                    System.out.println("Implementation-Title:   " + impTitle);
                }            
                if (impVersion != null)
                {
                    System.out.println("Implementation-Version: " + impVersion);
                }
                if (impBuildDate != null)
                {
                    System.out.println("Built-Date: " + impBuildDate);
                }
                if (impBuiltBy != null)
                {
                    System.out.println("Built-By:   " + impBuiltBy);
                }
    
                System.exit(0);
            }
            catch (IOException e)
            {            
                System.out.println("Couldn't read manifest.");
            }        
        }
    
        /**
         * @param args
         */
        public static void main(String[] args)
        {
            packageVersion version = new packageVersion();
            version.printVersion();        
        }
    
    }
    

    Here's the matching build.xml:

    
    
        
        
        
    
        
            
                
            
            
            
        
    
        
            
        
    
                
                  
            
            
            
                
                                                
                
                
                
                

提交回复
热议问题