Spring Boot 获取项目路径或文件
@GetMapping("/getPath") public void getPath() { // 获取路径三种方法方法,使用Spring Boot 方式,只有 pathA 部署到服务器获取到得路径是能直接使用得 String pathA = System.getProperty("user.dir"); String pathB = this.getClass().getClassLoader().getResource("").getPath(); String pathC = this.getClass().getResource("/").getPath().toString(); /* Linux结果 */ // pathA:/home/socket/cpiaojumanagement // pathB:file:/home/socket/cpiaojumanagement/manage-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/ // pathC:file:/home/socket/cpiaojumanagement/manage-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/ /* Window结果 */ // pathA:D:Idea_workSpacecpiaojumanagement // pathB:/D:/Idea_workSpace/cpiaojumanagement/target/classes/ // pathC:/D:/Idea_workSpace/cpiaojumanagement/target/classes/ // 可以读取到 resources/static/impTemplate/sp-template.xlsx 文件输入流 InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/impTemplate/sp-template.xlsx"); }
参考:https://blog.csdn.net/haoxiaoyong1014/article/details/107452595