codememo

스프링 부트 - ResourceLoader를 사용하여 텍스트 파일 읽기

tipmemo 2023. 7. 7. 19:04
반응형

스프링 부트 - ResourceLoader를 사용하여 텍스트 파일 읽기

다음과 같은 Spring 리소스 로더를 사용하여 텍스트 파일을 읽으려고 합니다.

Resource resource  = resourceLoader.getResource("classpath:\\static\\Sample.txt");

파일은 내 Spring boot 프로젝트에서 다음과 같이 위치합니다.

이클립스에서 애플리케이션을 실행할 때는 정상적으로 작동하지만, 애플리케이션을 패키징한 다음 java –jar를 사용하여 실행하면 file not found 예외가 발생합니다.

java.io.FileNotFoundException: class path resource [static/Sample.txt] cannot be resolved to absolute file path because it does not reside in the
 file system: jar:file:/C:/workspace-test/XXX/target/XXX-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static/Sample.txt

샘플이 있는 Jar 파일의 압축을 풉니다. XXX-0.0.1-SNAPshot\BOOT-INF\classes\static\Sample.txt

누가 저 좀 도와주실 수 있나요?

잘 부탁드립니다!

당신의 코드를 확인했습니다.Spring Boot JAR의 classpath에서 파일을 로드하려면 다음을 사용해야 합니다.resource.getInputStream()보다는resource.getFile().만약 당신이 사용하려고 한다면resource.getFile()Spring이 파일 시스템 경로에 액세스하려고 하지만 JAR의 경로에 액세스할 수 없기 때문에 오류가 발생합니다.

아래와 같은 세부 사항:

https://smarterco.de/java-load-file-classpath-spring-boot/

시도해 보십시오resourceLoader.getResource("classpath:static/Sample.txt");

실행할 때 이 코드로 작업java -jar XXXX.jar

enter image description here

업데이트 --------

당신의 코드를 검토한 후, 문제는 당신이 파일을 읽으려고 시도한다는 것입니다.FileInputStream하지만 실제로는 항아리 파일 안에 있습니다.

하지만 사실 당신은 이해합니다.org.springframework.core.io.Resource즉, InputStream을 얻을 수 있으므로 다음과 같이 할 수 있습니다.new BufferedReader(new InputStreamReader(resource.getInputStream())).readLine();

저도 같은 문제가 있었고 @Gipple Lake가 설명했듯이 Spring boot에서는 inputStream으로 파일을 로드해야 합니다.그래서 아래에 import.xml 파일을 읽고 싶은 예로 코드를 추가하겠습니다.

public void init() {
    Resource resource = new ClassPathResource("imports/imports.xml");
    try {
        InputStream dbAsStream = resource.getInputStream();
        try {
            document = readXml(dbAsStream);
            } catch (SAXException e) {
                trace.error(e.getMessage(), e);
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                trace.error(e.getMessage(), e);
                e.printStackTrace();
            }
    } catch (IOException e) {
        trace.error(e.getMessage(), e);
        e.printStackTrace();
    }
    initListeImports();
    initNewImports();
}

public static Document readXml(InputStream is) throws SAXException, IOException,
      ParserConfigurationException {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

      dbf.setValidating(false);
      dbf.setIgnoringComments(false);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setNamespaceAware(true);
      DocumentBuilder db = null;
      db = dbf.newDocumentBuilder();

      return db.parse(is);
  }

"를 추가했습니다.imports.xml고함을 지르다src/main/ressources/imports

파일을 아래에 두면 클래스 경로에 있을 것이고 아래와 같은 경로를 읽습니다.

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

Resource resource = new ClassPathResource("/static/pathtosomefile.txt");
resource.getURL().getPath()

여기서 답을 추가합니다.읽어보기ClassPathResource그리고 내용을 복사합니다.String.

try {
   ClassPathResource classPathResource = new ClassPathResource("static/Sample.txt");
   byte[] data = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
   String content = new String(data, StandardCharsets.UTF_8);
} catch (Exception ex) {
  ex.printStackTrace();
}

폴더의 모든 파일을 읽으려면

이것은 샘플 코드입니다.

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

@Controller
@RequestMapping("app/files")
public class FileDirController {
    @GetMapping("")
    public ModelAndView index(ModelAndView modelAndView) {

        ClassLoader cl = this.getClass().getClassLoader();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);

        Resource resources[] = new Resource[0];
        try {
            resources = resolver.getResources("files/*"); // src/main/resources/files
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (final Resource res : resources ) {
            System.out.println("resources" + res.getFilename());
        }


        modelAndView.setViewName("views/file_dir");

        return modelAndView;
    }
}

내부에 자원이 있는 경우resources/static/listings.csv

String path = "classpath:static/listings.csv";

ResultSet rs = new Csv().read(path, null, null);

언급URL : https://stackoverflow.com/questions/41754712/spring-boot-reading-text-file-using-resourceloader

반응형