动态获取打包Jar后的路径信息_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 动态获取打包Jar后的路径信息

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

 2011/7/11 11:07:51  kinganpo  http://kinganpo.iteye.com  我要评论(0)
  • 摘要:做了几个小软件需要用到打包后jar的路径,找了些日子终于到了可行方法...下面专门封装了一个类来处理:importjava.io.File;/***获取打包后jar的路径信息*@authorAdministrator*2011-01-1613:53:12*/publicclassJarTool{//获取jar绝对路径publicstaticStringgetJarPath(){Filefile=getFile();if(file==null)returnnull;returnfile
  • 标签:动态获取
做了几个小软件需要用到打包后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中的空格和中文“乱码”转换正确回显
对此可以为自己做的软件“注册”随系统开机启动了...
  • 大小: 9.4 KB
  • 查看图片附件
  • 相关文章
发表评论
用户名: 匿名