恼人的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
- 恼人的Java路径
- 一个恼人的错误~
- 恼人的课程设计
- 恼人的'素数回文'
- 恼人的Session start
- 恼人的时间格式
- 恼人的四级
- 恼人的ARP
- 恼人的浏览器缓存
- 恼人的环境变量
- 恼人的gnome
- 恼人的尾椎疼痛
- 恼人的设计模式
- 恼人的伪bug!
- 恼人的设计模式
- 恼人的设计模式
- 恼人的设计模式
- 恼人的雨
- 自己写wordcount程序在hadoop上运行
- Spring 的 BeanPostProcessor接口实现
- Linux执行.sh文件,提示No such file or directory的问题的解决方法
- 跟小刀 学习java导出word
- Vue.js学习总结(2)——Vue.js2.X + ElementUI开发环境搭建
- 恼人的Java路径
- Android开发论使用Java层的Zlib压缩和使用C底层的Zlib压缩的对比
- java UDP网络编程
- stack smashing datected.Aborted(core dumped)
- React Native Webview使用
- 如何使用SpannableString自定义文本样式
- 会用到的下载地址
- 码农技术炒股之路——抓取股票基本信息、实时交易信息、主力动向信息
- curl http get