java中的路径问题:
System.out.println(System.getProperty(“user.dir”));
//输出:F:\Java\project\study\iot_em
//当前项目绝对路径
System.out.println(request.getSession().getServletContext().getRealPath(""));
//输出:F:\Java\project\study\iot_em\src\main\webapp
//web程序路径,可指定文件URI,例如下一个例子
System.out.println(request.getServletContext().getRealPath("/upload/"));
//输出:F:\Java\project\study\iot_em\src\main\webapp\upload
//同上一个例子
System.out.println(this.getClass().getResource("").getPath());
//输出:/F:/Java/project/study/iot_em/target/classes/cn/koyanagi/iot_em/controller/
//获取当前类所在的绝对路径(编译后,在类加载器中)
//可指定文件URI,例如:this.getClass().getResource("/").getPath() 回到资源根目录
//将会输出:/F:/Java/project/study/iot_em/target/classes/
System.out.println(this.getClass().getClassLoader().getResource("").getPath());
//输出:/F:/Java/project/study/iot_em/target/classes/
//获取编译后资源根目录的绝对路径
//可指定URI,但URI前不能加"/",例如下一个例子
System.out.println(Thread.currentThread().getContextClassLoader().getResource(“static/”).getPath());
//输出:/F:/Java/project/study/iot_em/target/classes/static/
//同上一个例子
了解了路径问题后我们就可以获取资源了。资源文件一般放在/src/main/resource/template/
有四种获取方法
第一种:
ClassPathResource classPathResource = new ClassPathResource(“template/test.xlsx”);
InputStream inputStream =classPathResource.getInputStream();
第二种:
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(“template/test.xlsx”);
//相当于this.getClass().getClassLoader().getResourceAsStream(“template/test.xlsx”);
第三种:
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/template/test.xlsx");
第四种:
File file = ResourceUtils.getFile(“classpath:template/test.xlsx”);
InputStream inputStream = new FileInputStream(file);
第四种只有在开发环境(ide)时可以读取到,生产环境(部署到服务器后)读取失败
原文链接:https://blog.csdn.net/Junior_Liu/article/details/105827904