动态获取打包Jar后的路径信息

做了几个小软件需要用到打包后jar的路径,找了些日子终于到了可行方法... 
下面专门封装了一个类来处理: 
Java代码   收藏代码
  1. import java.io.File;  
  2. /** 
  3.  * 获取打包后jar的路径信息 
  4.  * @author Administrator 
  5.  *  2011-01-16 13:53:12 
  6.  */  
  7. public class JarTool {  
  8.     //获取jar绝对路径  
  9.     public static String getJarPath(){  
  10.         File file = getFile();  
  11.         if(file==null)return null;  
  12.          return file.getAbsolutePath();  
  13.     }  
  14.     //获取jar目录  
  15.     public static String getJarDir() {  
  16.         File file = getFile();  
  17.         if(file==null)return null;  
  18.          return getFile().getParent();  
  19.     }  
  20.     //获取jar包名  
  21.     public static String getJarName() {  
  22.         File file = getFile();  
  23.         if(file==null)return null;  
  24.         return getFile().getName();  
  25.     }  
  26.   
  27.     private static File getFile() {  
  28.         //关键是这行...  
  29.         String path = JarTool.class.getProtectionDomain().getCodeSource()  
  30.                 .getLocation().getFile();  
  31.         try{  
  32.             path = java.net.URLDecoder.decode(path, "UTF-8");//转换处理中文及空格  
  33.         }catch (java.io.UnsupportedEncodingException e){  
  34.             return null;  
  35.         }  
  36.         return new File(path);  
  37.     }  
  38.       
  39. }  

必须要打包成jar后才能正确获取相关路径信息,下面写了个测试类: 
Java代码   收藏代码
  1. import javax.swing.JFrame;  
  2. import javax.swing.JTextArea;  
  3.   
  4. public class TestFrame extends JFrame{  
  5.     public TestFrame() {  
  6.         JTextArea ta = new JTextArea();  
  7.         ta.setEditable(false);  
  8.         ta.append("name: "+JarTool.getJarName()+"\n");  
  9.         ta.append("dir: "+JarTool.getJarDir()+"\n");  
  10.         ta.append("path: "+JarTool.getJarPath()+"\n");  
  11.         add(ta);  
  12.         pack();  
  13.         setTitle("动态获取Jar路径信息");  
  14.         setVisible(true);  
  15.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  16.     }  
  17.     public static void main(String[] args) {  
  18.         new TestFrame();  
  19.     }  
  20. }  

将上面一起打包成path.jar后放到桌面运行结果: 
 
无论path.jar放到任何地方都能得到正确的路径信息 (*^__^*) 嘻嘻…… 
主要靠下面两行代码实现 
class.getProtectionDomain().getCodeSource().getLocation().getFile(); 这行作用是获取当前的绝对路径信息 
java.net.URLDecoder.decode(path, "UTF-8"); 此行是将path中的空格和中文“乱码”转换正确回显 
对此可以为自己做的软件“注册”随系统开机启动了...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值