1. 两种方式比较
1. String path = this.getClass().getClassLoader().getResource("").getPath();

返回:/F:/develop/local_project/mq/demo/target/classes/

2. String path1 = DemoApplication.class.getResource("").getPath();

返回:/F:/develop/local_project/mq/demo/target/classes/com/my/demo/

区别在于classLoader获取的是类的根路径,非classLoader获取的是当前类的绝对包路径。

3. String path1 = DemoApplication.class.getResource("/").getPath();

返回:/F:/develop/local_project/mq/demo/target/classes/

带了“/”号后,得到的结果和classLoader是一致的。

  1. 获取src同级目录下的文件方式:
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("./file/student.txt");

目录结构:
在这里插入图片描述
3. 总结:
(1)getResourceAsStream是用来获取classpath下的文件,如果编译后的配置文件不出现在classpath下面,则程序就无法获取到。

(2)注意如果路径中带有中文会被URLEncoder,因此这里需要解码

String filePath = URLDecoder.decode(path, "UTF-8");

(3)直接使用getResourceAsStream方法获取流,上面的几种方式都需要获取文件路径,但是在SpringBoot中所有文件都在jar包中,没有一个实际的路径,因此可以使用以下方式。

/**
     * 直接使用getResourceAsStream方法获取流
     * springboot项目中需要使用此种方法,因为jar包中没有一个实际的路径存放文件
     *
     * @param fileName
     * @throws IOException
     */
    public void function4(String fileName) throws IOException {
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
        getFileContent(in);
    }

也可以使用getResourceAsStream方法获取流,不使用getClassLoader可以使用getResourceAsStream(“/配置测试.txt”)直接从resources根路径下获取,SpringBoot中所有文件都在jar包中,没有一个实际的路径,因此可以使用以下方式。

 /**
     * 直接使用getResourceAsStream方法获取流
     * 如果不使用getClassLoader,可以使用getResourceAsStream("/配置测试.txt")直接从resources根路径下获取
     *
     * @param fileName
     * @throws IOException
     */
    public void function5(String fileName) throws IOException {
        InputStream in = this.getClass().getResourceAsStream("/" + fileName);
        getFileContent(in);
    }

也可以通过ClassPathResource类获取文件流,SpringBoot中所有文件都在jar包中,没有一个实际的路径,因此可以使用以下方式。(最优方案)

/**
     * 通过ClassPathResource类获取,建议SpringBoot中使用
     * springboot项目中需要使用此种方法,因为jar包中没有一个实际的路径存放文件
     *
     * @param fileName
     * @throws IOException
     */
    public void function6(String fileName) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(fileName);
        InputStream inputStream = classPathResource.getInputStream();
        getFileContent(inputStream);
    }

(4)通过new File(“”)获取当前的绝对路径,只是本地绝对路径,不能用于服务器获取。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐