Kinganpo
BlogJava
首页
新随笔
新文章
联系
聚合
管理
posts - 0,comments - 0,trackbacks - 0
<
2025年7月
>
日
一
二
三
四
五
六
29
30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
1
2
3
4
5
6
7
8
9
留言簿
给我留言
查看公开留言
查看私人留言
文章分类
swing(1)
文章档案
2011年1月 (1)
搜索
最新评论
动态获取打包Jar后的路径信息
做了几个小软件需要用到打包后jar的路径,找了些日子终于到了可行方法... 下面专门封装了一个类来处理:
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后才能正确获取相关路径信息,下面写了个测试类:
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中的空格和中文“乱码”转换正确回显
对此可以为自己做的软件“注册”随系统开机启动了...
原文地址:
http://kinganpo.javaeye.com/blog/876243
posted on 2011-01-22 20:25
Kinganpo
阅读(369)
评论(0)
编辑
收藏
所属分类:
swing
新用户注册
刷新评论列表
只有注册用户
登录
后才能发表评论。
网站导航:
博客园
IT新闻
Chat2DB
C++博客
博问
管理