我是Spring-boot / Java的新手,并试图在String中读取文件的内容。
问题是什么:我收到“找不到文件异常”并且无法读取该文件。显然,我没有提供正确的文件路径。
我已经附加了目录结构和我的代码。我在FeedProcessor文件中,想要阅读feed_template.php(见图)
public static String readFileAsString( ) {
String text = "";
try {
// text = new String(Files.readAllBytes(Paths.get("/src/main/template/feed_template_head.php")));
text = new String(Files.readAllBytes(Paths.get("../../template/feed_template_head.php")));
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
您需要将模板文件夹放在资源文件夹中。然后使用以下代码。
@Configuration
public class ReadFile {
private static final String FILE_NAME =
"classpath:template/feed_template_head.php";
@Bean
public void initSegmentPerformanceReportRequestBean(
@Value(FILE_NAME) Resource resource,
ObjectMapper objectMapper) throws IOException {
new BufferedReader(resource.getInputStream()).lines()
.forEach(eachLine -> System.out.println(eachLine));
}
}
我建议你去春天一次资源主题。 https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/resources.html