Spring Boot 讀取檔案路徑的四種方式

把檔案放在專案內的resources路徑下(\src\main\resources)

這裡新增了兩個檔案做示範

ruyut.json和static資料夾下的ruyut1.json

要讀取的檔案放置位置

如果要透過設定檔讀取檔案名稱和路徑,要把資訊寫在application.properties裡面

(\src\main\resources\application.properties)

示範的設定檔:

app.ruyut-file=ruyut.json
程式碼:

package com.ruyut.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

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

@Service
public class RuyutService {

    @Value("ruyut.json")
    private String ruyutFile;

    @Value("static/ruyut1.json")
    private String ruyutFile2;

    @Value("${app.ruyut-file}")
    private String ruyutFile3;

    @Bean
    public void initialize() {

        Resource resource = new ClassPathResource("ruyut.json"); // 直接寫檔名 路徑:src/main/resources/
//        Resource resource = new ClassPathResource(ruyutFile);//取得變數的檔名
//        Resource resource = new ClassPathResource(ruyutFile2);//取得變數的檔名(在static資料夾下)
//        Resource resource = new ClassPathResource(ruyutFile3);//使用springBoot的自動裝配,讀取設定檔內的文字
        File file = null;
        try {
            file = resource.getFile();
            System.out.println(file.getName());
            System.out.println(file.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}





留言