본문 바로가기
Spring

[Spring] ResourceLoader로 텍스트 파일 출력하기 (Java 11)

by Leica 2020. 3. 5.
반응형

[Spring] ResourceLoader로 텍스트 파일 출력하기 (Java 11)

Spring의 ApplicationContext는 ResourceLoader라는 인터페이스를 상속한다.

이 인터페이스는 이름에서부터 알 수 있듯 리소스를 읽어오는 기능을 제공한다.

 

1. Resource 객체 얻기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
 
@Component
public class AppRunner implements ApplicationRunner {
 
    @Autowired
    ResourceLoader resourceLoader;
 
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Resource resource = resourceLoader.getResource("classpath:test.txt");
        System.out.println(resource.exists());
    }
}
cs

ResourceLoader 기능을 사용하기 위해 Runner에 ResourceLoader 빈을 주입받는다.

ApplicationContext 타입으로 주입받아도 되지만 가장 구체적인 타입을 지정해서 직관적으로 코딩하는게 좋다.

ResourceLoader의 getResource() 메소드로 지정한 리소스의 Resource 객체를 얻을 수 있다.

지금은 일단 classpath에 존재하지 않는 텍스트 파일을 지정하여 Resource 객체를 얻어왔다.

Resource의 exists()는 지정한 리소스의 존재 여부를 boolean 타입으로 반환해주는데 지금은 당연히 false가 리턴된다.

 

다음으로 프로젝트의 resources 폴더에 test.txt 파일을 만들고 아무 내용이나 간략하게 작성해보자.

 

 

프로젝트를 빌드하면 resources 안의 파일들이 target 디렉토리로 복사된다.

 

빌드 전

 

빌드 후

 

target/classes가 classpath의 root가 되고, getResource()를 호출할 때 "classpath:"라는 접두어를 지정해줬으므로 target/classes에서 리소스를 찾는다.

 

2. 파일 내용 출력

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
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
 
import java.nio.file.Files;
import java.nio.file.Path;
 
@Component
public class AppRunner implements ApplicationRunner {
 
    @Autowired
    ResourceLoader resourceLoader;
 
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Resource resource = resourceLoader.getResource("classpath:test.txt");
        System.out.println(resource.exists());
 
        // 텍스트파일 내용 읽어서 출력 - Java 11 required
        System.out.println(Files.readString(Path.of(resource.getURI())));
    }
}
cs

 

resource.getURI()를 이용해서 리소스의 path를 만들어 파일 내용을 출력할 수 있다.

Path.of()와 Files.readString()을 사용하려면 Java 11 이상의 JDK가 필요하다.

 

References

인프런 - 백기선님의 스프링 프레임워크 핵심 기술

반응형

댓글