웹 개발

Spring Boot - jar 안의 파일 읽을 때 FileNotFoundException

노루아부지 2020. 12. 26. 00:37

일반적으로 Spring Boot는 resources에 파일을 위치시킵니다. resources 하위에 text 파일을 Spring에서 제공하는 ResourceLoader를 이용하여 Read 하는 코드가 있습니다.

 

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;

@Component
public class Runner implements ApplicationRunner {
    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        File file = resourceLoader.getResource("classpath:test.txt").getFile();
        System.out.println(file.isFile());
    }
}

 

위 예제를 IntelliJ나 Eclipse에서 구동시키면 정상적으로 결과값이 true로 출력됩니다.

하지만 이 예제를 export하여 jar에서 읽으려고 하면 FileNotFoundException이 발생합니다.

 

그 이유는 File class에 있습니다. File class는 File System에서 파일을 읽는데요 jar 파일은 일종의 압축파일이기 때문에 File System에서는 찾을 수 없는 방식인 것입니다.

 

 

 

 

해결 방법

 

해결방법은 간단합니다. getInputStream()을 사용하면 됩니다.

 

package com.example.demo;

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;

@Component
public class Runner implements ApplicationRunner {
    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        InputStream file = resourceLoader.getResource("classpath:test.txt").getInputStream();
        System.out.println(file.available());
    }
}

 

위와 같이 하면 파일을 읽을 수 있습니다. 여기서 available()의 결과 값은 파일에서 읽을 수 있는 byte의 크기입니다.

 

 

728x90
loading