Load file resource trong Spring Boot

Khi dev project dùng Spring Boot, ta có thể tận dụng đặt các file static trong thư mục "resources", bản thân lúc dev chạy bằng IDE thì đọc các file này sẽ không lỗi lầm gì.

Đến khi build ra file .jar (bootJar) và chạy thì có khả năng sẽ báo lỗi file not found nếu cách đọc chưa đúng.


Một cách phù hợp là inject ResourceLoader vào và đọc từ classpath, và phải dùng InputStream thay vì getFile, vì nếu đọc trực tiếp file thì đòi hỏi một path đến file đó trong khi các file trong resources lúc này được nhúng trong file .jar chứ ko có path thực tế trên filesytem.

Sample đoạn mã đọc file public_key.pem (resources/public_key.pem)

Resource resource = resourceLoader.getResource("classpath:public_key.pem");
InputStream inputStream = resource.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

List<String> lines = bufferedReader.lines().collect(Collectors.toList());

Tham khảo: https://smarterco.de/java-load-file-from-classpath-in-spring-boot/

Comments

Popular Posts

Liên hệ

Name

Email *

Message *