目录结构如图,想要读取resources目录下的input.json
一.获取当前项目的classpath绝对URI路径的5种方法
例如:file:/G:/jackson/target/classes/input.json
1.this.getClass().getResource("")
2.this.getClass().getResource("/")
3.this.getClass() .getClassLoader().getResource("")
4.ClassLoader.getSystemResource("")
5.Thread.currentThread().getContextClassLoader ().getResource("")
6.ServletActionContext.getServletContext().getRealPath(“/”)
Web应用程序 中,得到Web应用程序的根目录的绝对路径。这样,我们只需要提供相对于Web应用程序根目录的路径,就可以构建出定位资源的绝对路径。
注意:读取文件时,不能直接用以上获取的URI路径,需要做如下处理
这里在main方法里用的是第4种方法(静态方法),且直接把resource目录下的文件名作为参数传入,注意后面的getPath(),调用这个获取的是:
the path part of this URL, or an empty string if one does not exist
这个path才能用于获取文件
String path= ClassLoader.getSystemResource("input.json").getPath();
File file=new File(path);
二、参考文献
http://blog.sina.com.cn/s/blog_9c7605530101gg9d.html