获取运行jarfile的文件名

时间:2012-12-10 20:27:57

标签: java jar

有没有办法知道跨平台运行jar的文件名?

我可以获取路径,我可以获取目录中所有jar的名称,或者我可以将命令传递给操作系统上的命令提示符/ shell以尝试查找它,是否有更好的方法此?

1 个答案:

答案 0 :(得分:1)

看看这里:http://mindprod.com/jgloss/wherejars.html

public class Where
   {
   /**
    * main
    * @param args name of fully qualified class to find, using dots, but no dot class.
    * e.g. java.exe Where javax.mail.internet.MimeMessage
     */
   public static void main ( String[] args )
      {
      try
         {
         String qualifiedClassName = args[0];
         Class qc = Class.forName( qualifiedClassName );
         CodeSource source = qc.getProtectionDomain().getCodeSource();
         if ( source != null )
            {
            URL location = source.getLocation();
            System.out.println ( qualifiedClassName + " : " + location );
            }
         else
            {
            System.out.println ( qualifiedClassName + " : " + "unknown source, likely rt.jar" );
            }
         }
      catch ( Exception e )
         {
         System.err.println( "Unable to locate class on command line." );
         e.printStackTrace();
         }
      }
   }