动态获取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后才能正确获取相关路径信息,下面写了个测试类:
- Java代码 收藏代码
- 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中的空格和中文“乱码”转换正确回显
- 对此可以为自己做的软件“注册”随系统开机启动了...
分类:
JAVA
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】