六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 26|回复: 0

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

[复制链接]

升级  68%

8

主题

8

主题

8

主题

童生

Rank: 1

积分
34
 楼主| 发表于 2013-2-3 13:35:58 | 显示全部楼层 |阅读模式
做了几个小软件需要用到打包后jar的路径,找了些日子终于到了可行方法...
下面专门封装了一个类来处理:
import java.io.File;/** * 获取打包后jar的路径信息 * @author Administrator *2011-01-16 13:53:12 */public class JarTool {//获取jar绝对路径public static String getJarPath(){File file = getFile();if(file==null)return null; return file.getAbsolutePath();}//获取jar目录public static String getJarDir() {File file = getFile();if(file==null)return null;     return getFile().getParent();}//获取jar包名public static String getJarName() {File file = getFile();if(file==null)return null;return getFile().getName();}private static File getFile() {//关键是这行...String path = JarTool.class.getProtectionDomain().getCodeSource().getLocation().getFile();        try{            path = java.net.URLDecoder.decode(path, "UTF-8");//转换处理中文及空格        }catch (java.io.UnsupportedEncodingException e){            return null;        }return new File(path);}}
必须要打包成jar后才能正确获取相关路径信息,下面写了个测试类:
import javax.swing.JFrame;import javax.swing.JTextArea;public class TestFrame extends JFrame{public TestFrame() {JTextArea ta = new JTextArea();ta.setEditable(false);ta.append("name: "+JarTool.getJarName()+"\n");ta.append("dir: "+JarTool.getJarDir()+"\n");ta.append("path: "+JarTool.getJarPath()+"\n");add(ta);pack();setTitle("动态获取Jar路径信息");setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public static void main(String[] args) {new TestFrame();}}
将上面一起打包成path.jar后放到桌面运行结果:

无论path.jar放到任何地方都能得到正确的路径信息 (*^__^*) 嘻嘻……
主要靠下面两行代码实现
class.getProtectionDomain().getCodeSource().getLocation().getFile();这行作用是获取当前的绝对路径信息
java.net.URLDecoder.decode(path, "UTF-8");此行是将path中的空格和中文“乱码”转换正确回显
对此可以为自己做的软件“注册”随系统开机启动了...
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表