一、在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>
五、运行结果