Java項目讀取resources下的配置文件

資源文件準備

20190815194618.png

{
  "name": "Tom",
  "age": 19
}

讀取方式

一、Java原生

使用 java 的 ClassLoader 來讀取

public static void main(String[] args) throws IOException {
    String path = AreaCode.class.getClassLoader().getResource("student.json").getPath();
    // FileUtils 用的是 Apache common-io 包
    String string = FileUtils.readFileToString(new File(path), CharEncoding.UTF_8);
    System.out.println(string);
}

二、Spring

// 這種方式,當項目打成 jar 包放到服務器後就找不到文件了,打成jar包後必須以流的方式讀取文件,看下面第三種方式。
public static void main(String[] args) {
    try {
        // org.springframework.core.io 包
        Resource resource = new ClassPathResource("student.json");
        File file = resource.getFile();
        // FileUtils 用的是 Apache common-io 包
        String string = FileUtils.readFileToString(file, CharEncoding.UTF_8);
        System.out.println(string);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

三、以流的方式讀取

tips: jar包的情況下linux下不能得到resource下的文件的路徑, 打成jar包後必須以流的方式讀取文件

ClassLoader 獲取文件流

public static void main(String[] args) throws IOException {
    // 這種方式也是使用 java 的 ClassLoader 來讀取
    InputStream inputStream = AreaCode.class.getClassLoader().getResourceAsStream("student.json");
    StringBuilder out = new StringBuilder();
    byte[] b = new byte[4096];
    // 讀取流
    for (int n; (n = inputStream.read(b)) != -1; ) {
        out.append(new String(b, 0, n));
    }
    System.out.println(out.toString());
}

Spring 獲取文件流

與上面 Spring 方式類似,只是把文件轉換成輸入流了

public static void main(String[] args) throws IOException {
    Resource resource = new ClassPathResource("student.json");
    InputStream inputStream = resource.getInputStream();
    StringBuilder out = new StringBuilder();
    byte[] b = new byte[4096];
    // 讀取流
    for (int n; (n = inputStream.read(b)) != -1; ) {
        out.append(new String(b, 0, n));
    }
    System.out.println(out.toString());
}

上面的輸出結果均爲:

20190815194812.png

Properties文件

Properties 文件讀取不必使用上面的方法,有更簡單的方法,具體看我另外一篇博客:
Java 讀取 Properties 文件

感謝

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章