恼人的Java路径

来源:互联网 发布:网络推广视频 编辑:程序博客网 时间:2024/05/18 03:12

Java路径问题,超级烦人。

将打包的yqj2065.jar添加到当前项目的库中,就能够方便地复用它们。如果要通过控制台运行yqj2065.jar,就麻烦来了。

运行打包的yqj2065.jar和在BlueJ项目、NetBeans项目中运行,路径问题多多。


在D盘根目录下创建BlueJ项目path,创建yqj2065.util包,有文件Main.java。打包时取名yqj2065.jar,放在d:\path文件夹中。另外有一个NetBeans项目将比较运行的输出。

1.System.getProperty

pln(System.getProperty("user.dir"));
这是最常用的方式。返回一个String

Windows命令行D:\path>java -jar yqj2065.jar

输出: D:\path

两个小问题:1)因为Windows中用\,获得的路径字符串不能够直接使用,要转换为"D:\\path".2)假设有人使用过System.setProperty就悲剧了。

2.ClassLoader. getResource

方法public URL getResource(String name) 或配套的 InputStream getResourceAsStream(String name)常用。

这种方式有很多的变体。

        URL location = Thread.currentThread().getContextClassLoader().getResource("");        URL location2 = Main.class.getClassLoader().getResource("");        URL location3 =  Main.class.getResource("");        pln(location.getPath());         pln(location2.getPath());         pln(location3.getPath()); 
在项目环境中,这些方法好用。前两个相当于class文件的根目录,第三个相当于本Main.class文件所在的目录。如BlueJ中输出

/D:/path/     在项目中直接通过文件名访问的,就是这个文件夹
/D:/path/
/D:/path/yqj2065/util/
NetBeans项目中会加上 build/classes/

但是,运行yqj2065.jar得到的都是null。NullPointerException

如果有文件D:/path/my.properties、D:/path/yqj2065/util/readme.txt

        URL location = Thread.currentThread().getContextClassLoader().getResource("my.properties");        URL location2 = Main.class.getClassLoader().getResource("my.properties");        URL location3 =  Main.class.getResource("README.TXT");//区分大小写?        pln(location.getPath());         pln(location2.getPath());         pln(location3.getPath()); 
BlueJ中输出

/D:/path/my.properties
/D:/path/my.properties
/D:/path/yqj2065/util/readme.txt  //getResource("readme.TXT"),ok

运行yqj2065.jar输出

file:/D:/path/yqj2065.jar!/my.properties
file:/D:/path/yqj2065.jar!/my.properties
file:/D:/path/yqj2065.jar!/yqj2065/util/README.TXT   //

注意yqj2065.jar!,后面有一个惊叹号。

3.Main.class.getProtectionDomain().getCodeSource().getLocation()

运行yqj2065.jar时,一个好的选择是:

        URL location1 = Main.class.getProtectionDomain().getCodeSource().getLocation();        pln(location1.getFile());
BlueJ项目中输出: /D:/path/

运行yqj2065.jar输出:/D:/path/yqj2065.jar


0 0
原创粉丝点击