Java中获得路径

1、在java中经常会看到这样的代码 File file=new File("local/app.txt")。那么这个文件的路径是相对于系统属性key为user.dir的路径。代码如下:

                // 打印当前的路径
		File currentFile = new File("");
		printer.println(currentFile.getAbsolutePath());
		// 打印出user.dir属性
		printer.println(System.getProperty("user.dir"));

 如果我们修改user.dir的属性重新执行以上的代码会发现路径也会发生改变。File rootFile = new File("/");windows表示盘符的目录。

2、获得classpath下资源的路径

                 // 打印当前class路径的url
		printer.println(PathPrinter.class.getResource("").toString());

		// 下面的语句和getClassLoader().getResource("")相同,因为                                      // CLass.getResource做了下处理。参见起Class类resolveName方法
		printer.println(PathPrinter.class.getResource("/").toString());

 3、通过classLoader的API获得资源

                    printer.println(PathPrinter.class.getClassLoader().getResource("").toString());

我们的源码工程如下:

 里面代码请查看附件。

如果我们把该代码导出jar包然后供其他代码使用,




 
 然后此时调用会发现在这一行代码会报空指针( java.lang.NullPointerException)PathPrinter.class.getResource("")。经过跟踪代码发现此时我们使用的ClassLoader是sun.misc.Launcher.AppClassLoader。而这个ClassLoader查找资源是根据classPath查找,此时的ClassPath包含一个jar包,在sun.misc.URLClassPath.JarLoader中loader路径是为空的,在getResource方法中,代码如下:

   //此时paramString为class文件的相对路径
   JarEntry localJarEntry = this.jar.getJarEntry(paramString);
   //JarFile的getJarEntry方法如果入参是路径,得到的为空

 因此通过上面PathPrinter.class.getResource("")获得类所在的路径不一定都是可以的(如果该jar放入到osgi环境下,这段代码还是没有问题的)

猜你喜欢

转载自fengozl.iteye.com/blog/2211253