读配置文件推荐做法:
1. Test.class.getResource("")
获取Test类所在路径
2. Test.class.getResource("/")
获取classpath的绝对路径
3. Thread.currentThread().getContextClassLoader().getResource("")
同上
4. Test.class.getClassLoader().getResource("")
同上
5. ClassLoader.getSystemResource("")
同上
在Web应用程序中,通过ServletContext.getRealPath("/")方法得到Web应用程序的根目录的绝对路径。这样,我们只需要提供相对于Web应用程序根目录的路径,就可以构建出定位资源的绝对路径。
注:
1. 尽量不要使用相对于System.getProperty("user.dir")当前用户目录的相对路径
2. 尽量使用URI形式的绝对路径资源,它可以很容易的转变为URI,URL,File对象
3. 尽量使用相对classpath的相对路径,不要使用绝对路径
4. 绝对不要使用硬编码的绝对路径
5. 推荐使用程序得到classpath的绝对路径来拼资源的绝对路径