AdSense

網頁

2020/1/3

Spring Boot 讀取resources目錄的檔案 read file in resources

在Spring讀取src/main/resources下的檔案的方式如下。



src/main/resources為Spring專案預設的靜態資源路徑,與src/main/java一樣都是classpath根目錄,可以透過@Value注入,ResourceLoaderClassPathResource取得目錄下的檔案。


例如下面是Spring Boot專案的Controller類別,getSpringImage()為取得src/main/resources/static路徑下的spring.png圖檔的方法,分別用了上述各種方法取得src/main/resources/static/spring.png圖片檔案。

DemoController.java

package com.abc.demo.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@RestController
public class DemoController {

    @Value("classpath:static/spring.png")
    private Resource resource;

    @Autowired
    private ResourceLoader resourceLoader;

    @GetMapping(value="/spring", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getSpringImage() throws IOException {
        byte[] bytes = null;

        bytes = getResourceFileBytesByResource();
        // bytes = getResourceFileBytesByResourceLoader();
        // bytes = getResourceFileBytesByClassPathResource();

        return bytes;
    }

    private byte[] getResourceFileBytesByResource() throws IOException {
        File file = resource.getFile();
        printFileInfo(File file);

        InputStream in = resource.getInputStream();
        return IOUtils.toByteArray(in);
    }

    private byte[] getResourceFileBytesByResourceLoader() throws IOException {
        Resource resource = resourceLoader.getResource("classpath:static/spring.png"); // 取得src/main/resources/static/spring.png的Resource
        File file = resource.getFile();
        printFileInfo(File file);

        InputStream in = resource.getInputStream();
        return IOUtils.toByteArray(in);
    }

    private byte[] getResourceFileBytesByClassPathResource() throws IOException {
        Resource resource = new ClassPathResource("static/spring.png"); // 取得src/main/resources/static/spring.png的Resource
        File file = resource.getFile();
        printFileInfo(File file);

        InputStream in = resource.getInputStream();
        return IOUtils.toByteArray(in);
    }

    private void printFileInfo(File file) {
        System.out.println(file.getName()); // spring.png (檔案名稱)
        System.out.println(file.getPath()); // /Users/.../workspace/demo/target/classes/static/spring.png (檔案系統的路徑)
        System.out.println(file.length()); // 21113 (檔案大小21113bytes)
    }
}

ClassPathResource(String path)建構式的path參數為以classpath為根的資源路徑位置。


參考:

沒有留言:

AdSense