springboot获取文件流

在日常开发中,经常会获取项目的相对路径用以获取存放在项目路径下的资源,如获取static/ss.txt

springboot获取文件流

在spring项目中,  可以用request.getRealPath("/")获取项目路径然后拼接起来,再生成流:

       //拼接地址

       String downLoadUrl = request.getRealPath("/") + "/static/ss.txt/" ;
        // 生成流
        InputStream is = new FileInputStream(downLoadUrl);

 在springBoot中,request.getRealPath("/") 不能获取到项目路径,查资料得知ResourceUtils.getURL("classpath:").getPath()能获取到项目路径,测试中发现,ResourceUtils.getURL("classpath:").getPath()获取到的是项目的绝对路径,打包发版提示:

java.io.FileNotFoundException: file:/usr/local/risk_dubbo/risk-admin/20181105_161334risk-admin.war!/WEB-INF/classes!/static/ss.txt (No such file or directory)

不能用以获取项目中的资源路径。各种查资料测试得出:

String downLoadUrl = "/static/ss.txt" ;

InputStream is = this.getClass().getResourceAsStream(downLoadUrl);

可获取输入流。