springboot读取classpath目录下文件

假设静态资源文件 information.txt 放在 src/main/resources 目录下

 public String getInfo() {
        String msg = "";
        InputStreamReader intput = null;
        try {
            Resource resource = new ClassPathResource("information.txt");
            File file = resource.getFile();
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            msg = reader.readLine();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    return msg;
}

注意:

如果将该项目打包运行在Linux系统下,该方法无法读取文件,报错信息为cannot be resolved to absolute file path because it does not reside in the file system。这是因为在Linux系统下,spring无法访问jar中的路径。

解决方法:

使用ClassPathResource类的getInputStream方法获取InputStream

Linux读取resources目录下文件:

 public String getInfo() {
        String msg = "";
        InputStreamReader intput = null;
        try {
            Resource resource = new ClassPathResource("information.txt");
            // 修改部分
            intput = new InputStreamReader(resource.getInputStream());		
            BufferedReader reader = new BufferedReader(intput);
            msg=  reader.readLine();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    return msg;
}

 

你可能感兴趣的:(springboot)