今天项目又遇到了,,,读取项目下文件的情况下。 其实这个挺头疼的,,,特别是 Java web项目 下的方式和 Java 项目 下 读取文件的相对路径是有点区别的。。。所以感觉挺不好搞的。。。
而且 我们使用 第三方的 类库,工具类的时候,需要将 文件的路径给传递进去的。。。 可是 这时候 使用相对路径怎么写? 如果使用 绝对的路径又怎么写呢? 使用 非常原生的方式? 拼路径? 比如 求出 Java web的项目的当前的绝对路径,,, 或者求出当前 class 类的 根路径吗。 其实都挺不好用的。 其实我们可以是用 spring的 工具类来获取到 文件的。不用我们再次 写实现代码了。而且spring 读取文件 classpath 下面的 文件 功能还是很强大的。。。
try {
// 1, 使用spring工具类 来获取文件
File cfgFile = ResourceUtils.getFile("classpath:config/allinpay/20060400000044502.p12");
System.out.println(cfgFile.getAbsolutePath());
System.out.println(cfgFile.getCanonicalPath());
System.out.println(cfgFile.getPath());
System.out.println(cfgFile.getParent());
System.out.println(cfgFile.getName());
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println("文件没找到");
e1.printStackTrace();
}
String bString = "";
try {
//2, 获取 classpath的 根路径然后 文件的 绝对路径求出来。
bString = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();
System.out.println(Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath());
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(req.getServletPath());
System.out.println(req.getSession().getServletContext().getRealPath(""));
File file = new File(bString + "config/allinpay/allinpay-pds.cer");
File file2 = new File("/config/allinpay/allinpay-pds.cer");
System.out.println(file.exists());
System.out.println(file2.exists());