Spring boot 讀文件

每次都忘, 找起來太費事, 因爲太亂.

簡單說, 就是不打成jar包的時候, 可以返回File, 打成jar包只能返回InputStream. -- 要是把返回File那個方法去掉多好.就不用tmd本地ok, 發佈的時候懵逼了.

當然,誰讓我記性不好呢.

ClassPathResource resource = new ClassPathResource(filePath);

resource.getInputStream(); //返回Stream

private List<String> readAll(String filePath) {
        if (Objects.isNull(filePath)) {
            return Collections.emptyList();
        }

        try {
            ClassPathResource resource = new ClassPathResource(filePath);
            List<String> strings = IOUtils.readLines(resource.getInputStream(), "UTF-8");
            return strings;
        } catch (IOException e) {
            log.error("resource file error: {}", filePath, e);
        }
        return Collections.emptyList();
    }

別的方法也有很多, 不總結了.

比如

@Value 比較適合配置文件

@Value("${contentFilePath}")
private String fileContent;



// on application-local.properties
contentFilePath=classpath:someDir/contentFile.config

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章