当前位置: 移动技术网 > IT编程>开发语言>Java > 基于获取JAVA路径,包括CLASSPATH外的路径的方法详解

基于获取JAVA路径,包括CLASSPATH外的路径的方法详解

2019年07月22日  | 移动技术网IT编程  | 我要评论
归纳一些网上取java路径的方法:
注明:如果从ant启动程序,this.getclass().getresource("")取出来的比较怪,直接用java命令行调试就可成功。
得到classpath和当前类的绝对路径的一些方法
获得classpath之外路径的方法:
url base = this.getclass().getresource(""); //先获得本类的所在位置,如/home/popeye/testjava/build/classes/net/ string path = new file(base.getfile(), "……/……/……/"+name).getcanonicalpath(); //就可以得到/home/popeye/testjava/name
下面是一些得到classpath和当前类的绝对路径的一些方法。你可能需要使用其中的一些方法来得到你需要的资源的绝对路径。
1.filetest.class.getresource("")
得到的是当前类filetest.class文件的uri目录。不包括自己!
如:file:/d:/java/eclipse32/workspace/jbpmtest3/bin/com/test/
2.filetest.class.getresource("/")
得到的是当前的classpath的绝对uri路径。
如:file:/d:/java/eclipse32/workspace/jbpmtest3/bin/
3.thread.currentthread().getcontextclassloader().getresource("")
得到的也是当前classpath的绝对uri路径。
如:file:/d:/java/eclipse32/workspace/jbpmtest3/bin/
4.filetest.class.getclassloader().getresource("")
得到的也是当前classpath的绝对uri路径。
如:file:/d:/java/eclipse32/workspace/jbpmtest3/bin/
5.classloader.getsystemresource("")
得到的也是当前classpath的绝对uri路径。
如:file:/d:/java/eclipse32/workspace/jbpmtest3/bin/
我推荐使用thread.currentthread().getcontextclassloader().getresource("")来得到当前的classpath的绝对路径的uri表示法。
在web应用程序中,我们一般通过servletcontext.getrealpath("/")方法得到web应用程序的根目录的绝对路径。这样,我们只需要提供相对于web应用程序根目录的路径,就可以构建出定位资源的绝对路径。
注意点:
1.尽量不要使用相对于system.getproperty("user.dir")当前用户目录的相对路径。这是一颗定时炸弹,随时可能要你的命。
2.尽量使用uri形式的绝对路径资源。它可以很容易的转变为uri,url,file对象。
3.尽量使用相对classpath的相对路径。不要使用绝对路径。使用上面classloaderutil类的public static url getextendresource(string relativepath)方法已经能够使用相对于classpath的相对路径定位所有位置的资源。
4.绝对不要使用硬编码的绝对路径。因为,我们完全可以使用classloader类的getresource("")方法得到当前classpath的绝对路径。
使用硬编码的绝对路径是完全没有必要的!它一定会让你死的很难看!程序将无法移植!
如果你一定要指定一个绝对路径,那么使用配置文件,也比硬编码要好得多!
当然,我还是推荐你使用程序得到classpath的绝对路径来拼资源的绝对路径

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网