티스토리 뷰

resources > res.txt 파일을 읽기 위해서 아래와 같이 ResourceLoader를 이용하여 classpath에 있는 파일을 읽을 수 있습니다.

package com.example.logbacksample;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.File;

@Slf4j
@Component
public class ResourceApplicationRunner implements ApplicationRunner {
    @Autowired
    ResourceLoader resourceLoader;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        File file = resourceLoader.getResource("classpath:res.txt").getFile();
        log.info("exist : " + file.exists());
    }
}

 

그런데, IDE에서 잘 동작되던 코드는 jar를 만들어 실행해보면 FileNotFoundException이 발생합니다.

( Caused by: java.io.FileNotFoundException: class path resource [res.txt] cannot be resolved to absolute file path because it does not reside in the file system )

 

이를 해결하기 위해서는 아래와 같이 resource의 InputStream을 가지고 와서 파일의 내용을 읽을 수 있습니다.

package com.example.logbacksample;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Slf4j
@Component
public class ResourceApplicationRunner implements ApplicationRunner {
    @Autowired
    ResourceLoader resourceLoader;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        InputStream inputStream = resourceLoader.getResource("classpath:res.txt").getInputStream();
        byte[] data = new byte[100];
        log.info("data : " + inputStream.read(data));
    }
}

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함