http://blog.csdn.net/whuslei/article/details/7337715
一般执行jar包有下面两种方式:
1、cd 到包含该jar包的目录里,执行命令
java -jar Demorun_fat.jar
2、直接加入绝对路径(比如把jar包直接拖入cmd窗口,就可以得到jar包的路径了)并执行命令
所以,如果直接取相对路径就会得到两个结果,前者会是“E:\workspace4svn\Demorun\”,后者是"当前目录,如C:\"。
解决办法
下面以一个jar包和一个data/in.txt为例来说明下面两种方法:
方法一:
在eclipse里运行(不打包)的结果是: “E:\workspace4svn\Demorun\bin;E:\workspace4svn\Hello\Hello_fat.jar” (注意:Hello_fat.jar不是可执行的jar,是从外部引入的包)
在cmd里运行jar包的结果是:“E:\workspace4svn\Demorun\Demorun_fat.jar”
[小结]
(1) 这种方法在eclipse中运行结果的意思是"Path used to find directories and JAR archives containing class files.",也就是结果包括了可执行.class文件的路径以及引入的jar包路径。
(2) 打包成jar包后,结果是jar包执行的路径!而且可以识别中文!
(3) 过于System.getProperty的用法参见http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
参考代码如下:
- import java.io.File;
- import java.net.URL;
- import java.net.URLDecoder;
- public class MyPath {
- public static String getPath(){
- String filePath = System.getProperty("java.class.path");
- String pathSplit = System.getProperty("path.separator");//windows下是";",linux下是":"
- if(filePath.contains(pathSplit)){
- filePath = filePath.substring(0,filePath.indexOf(pathSplit));
- }else if (filePath.endsWith(".jar")) {//截取路径中的jar包名,可执行jar包运行的结果里包含".jar"
- //此时的路径是"E:\workspace\Demorun\Demorun_fat.jar",用"/"分割不行
- //下面的语句输出是-1,应该改为lastIndexOf("\\")或者lastIndexOf(File.separator)
- // System.out.println("getPath2:"+filePath.lastIndexOf("/"));
- filePath = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1);
- }
- return filePath;
- }
- }
方法二:『力荐』
在eclipse里运行(不打包)的结果是: “/E:/workspace/Demorun/bin/”
在cmd里运行jar包的结果是:“/E:/workspace/Demorun/Demorun_fat.jar”
如果不加.getPath,则结果是"file:/E:/workspace/Demorun/bin/"和"file:/E:/workspace/Demorun/Demorun_fat.jar",也就是说结果前面多了个"file:"
[小结]
(1) 这种方法不支持中文,需要转化下。
(2) 特别注意结果中的"斜线",方法一是windows中路径的正确表示,用"\"分割;方法二里是用"/"来分割,不是正确的路径!所以需要用file.getAbsolutePath();转化!
(3) 结果差异不大,在eclipse中的结果是.MainClass所在目录,而jar包运行的结果是jar包的完整路径。很容易可以得出程序运行的目录!具体程序如下:
- import java.io.File;
- import java.net.URL;
- import java.net.URLDecoder;
- public class MyPath {
- public static String getPath() {
- URL url = MyPath.class.getProtectionDomain().getCodeSource().getLocation();
- String filePath = null;
- try {
- filePath = URLDecoder.decode(url.getPath(), "utf-8");// 转化为utf-8编码
- } catch (Exception e) {
- e.printStackTrace();
- }
- if (filePath.endsWith(".jar")) {// 可执行jar包运行的结果里包含".jar"
- // 截取路径中的jar包名
- filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
- }
- File file = new File(filePath);
- // /If this abstract pathname is already absolute, then the pathname
- // string is simply returned as if by the getPath method. If this
- // abstract pathname is the empty abstract pathname then the pathname
- // string of the current user directory, which is named by the system
- // property user.dir, is returned.
- filePath = file.getAbsolutePath();//得到windows下的正确路径
- return filePath;
- }
- }