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

做了几个小软件需要用到打包后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后放到桌面运行结果:
[img]http://dl.iteye.com/upload/attachment/392062/f2e7c82e-b67b-3d42-b50d-147c80cff179.png[/img]
无论path.jar放到任何地方都能得到正确的路径信息 (*^__^*) 嘻嘻……
主要靠下面两行代码实现
[b]class.getProtectionDomain().getCodeSource().getLocation().getFile();[/b]这行作用是获取当前的绝对路径信息
[b]java.net.URLDecoder.decode(path, "UTF-8");[/b]此行是将path中的空格和中文“乱码”转换正确回显
对此可以为自己做的软件“注册”随系统开机启动了...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值