动态获取jar文件的路径

  1. 下面专门封装了一个类来处理:  
  2. import  java.io.File;    
  3. /**   
  4.  * 获取打包后jar的路径信息   
  5.  * @author Administrator   
  6.  *  2011-01-16 13:53:12   
  7.  */     
  8. public   class  JarTool {    
  9.     //获取jar绝对路径     
  10.     public   static  String getJarPath(){    
  11.         File file = getFile();    
  12.         if (file== null ) return   null ;    
  13.          return  file.getAbsolutePath();    
  14.     }    
  15.     //获取jar目录     
  16.     public   static  String getJarDir() {    
  17.         File file = getFile();    
  18.         if (file== null ) return   null ;    
  19.          return  getFile().getParent();    
  20.     }    
  21.     //获取jar包名     
  22.     public   static  String getJarName() {    
  23.         File file = getFile();    
  24.         if (file== null ) return   null ;    
  25.         return  getFile().getName();    
  26.     }    
  27.     
  28.     private   static  File getFile() {    
  29.         //关键是这行...     
  30.         String path = JarTool.class .getProtectionDomain().getCodeSource()    
  31.                 .getLocation().getFile();    
  32.         try {    
  33.             path = java.net.URLDecoder.decode(path, "UTF-8" ); //转换处理中文及空格     
  34.         }catch  (java.io.UnsupportedEncodingException e){    
  35.             return   null ;    
  36.         }    
  37.         return   new  File(path);    
  38.     }    
  39.         
  40. }    
  41. 必须要打包成jar后才能正确获取相关路径信息,下面写了个测试类:  
  42. Java代码  收藏代码  
  43. import  javax.swing.JFrame;    
  44. import  javax.swing.JTextArea;    
  45.     
  46. public   class  TestFrame  extends  JFrame{    
  47.     public  TestFrame() {    
  48.         JTextArea ta = new  JTextArea();    
  49.         ta.setEditable(false );    
  50.         ta.append("name: " +JarTool.getJarName()+ "/n" );    
  51.         ta.append("dir: " +JarTool.getJarDir()+ "/n" );    
  52.         ta.append("path: " +JarTool.getJarPath()+ "/n" );    
  53.         add(ta);    
  54.         pack();    
  55.         setTitle("动态获取Jar路径信息" );    
  56.         setVisible(true );    
  57.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
  58.     }    
  59.     public   static   void  main(String[] args) {    
  60.         new  TestFrame();    
  61.     }    
  62. }    
  63. 将上面一起打包成path.jar后放到桌面运行结果:  
  64. 无论path.jar放到任何地方都能得到正确的路径信息 (*^__^*) 嘻嘻……  
  65. 主要靠下面两行代码实现  
  66. class.getProtectionDomain().getCodeSource().getLocation().getFile(); 这行作用是获取当前的绝对路径信息  
  67. java.net.URLDecoder.decode(path, "UTF-8"); 此行是将path中的空格和中文“乱码”转换正确回显  
  68. 对此可以为自己做的软件“注册”随系统开机启动了...   
原文地址:https://www.cnblogs.com/zhwl/p/3635047.html