1. 程式人生 > 其它 >java 讀取 resources 下面的 json 檔案

java 讀取 resources 下面的 json 檔案

一、在main目錄下建立 resources 並設為資源目錄

 

 

 

 二、直接上程式碼

引用

import org.springframework.util.ResourceUtils;

全部程式碼

package com.ConfigJson;

import java.io.*;
import java.util.Properties;

import org.springframework.util.ResourceUtils;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( 
"Hello World!" ); String json = readJsonFile("app_agentlist.json"); System.out.println(json); } /** * 讀取 JSON 配置檔案 */ public static String readJsonFile(String fileName) { FileReader fileReader = null; Reader reader = null; try { File jsonFile
= ResourceUtils.getFile("classpath:"+fileName); fileReader = new FileReader(jsonFile); reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8"); int ch; StringBuffer sb = new StringBuffer(); while ((ch = reader.read()) != -1) { sb.append((
char) ch); } fileReader.close(); reader.close(); String jsonStr = sb.toString(); return jsonStr; } catch (IOException e) { e.printStackTrace(); //logger.error("讀取檔案報錯", e); System.out.println("讀取檔案報錯!"+e); } finally { if(fileReader != null){ try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } if(reader != null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } }

三、app_agentlist.json

{
  "name": "resources",
  "version": "1.0.0",
  "dependencies": {

  }
}

四、pom.xml  (重點:,始終讀取不到 json 檔案,報錯,是因為 pom.xml 檔案裡面沒有配置 )

<resources>
      <resource>
        <filtering>true</filtering>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.json</include>
        </includes>
      </resource>
 </resources>

 

 五、執行結果

 

 感謝:

https://www.cnblogs.com/yuxiaole/p/9719954.html