Относительный путь к файлу | Springboot

#java #spring-boot #filereader

#java #spring-boot #программа чтения файлов

Вопрос:

Я новичок в Spring-boot / Java и пытаюсь прочитать содержимое файла в строке.

В чем проблема: я получаю «Исключение File not found» и не могу прочитать файл. По-видимому, я не указываю правильный путь к файлу.

я прикрепил структуру каталогов и свой код. Я нахожусь в файле 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;
  }
  

введите описание изображения здесь

Ответ №1:

Вам нужно поместить папку шаблона в папку ресурсов. А затем используйте следующий код.

 @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));

}
}
  

Я предлагаю вам хотя бы раз перейти к теме ресурса в spring.
https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/resources.html