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

来源:互联网 发布:vm安装linux虚拟机 编辑:程序博客网 时间:2024/05/18 05:41
做了几个小软件需要用到打包后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中的空格和中文“乱码”转换正确回显 
对此可以为自己做的软件“注册”随系统开机启动了...
0 0
原创粉丝点击