方式1: // 读取resources下
pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
config.json
{
"ukeyConf": {
"ukeyPassword": "123456",
"ukeyTTL": 2592000000
},
"redisXuite": {
"cache": {
"serverHost": "127.0.0.1",
"serverPort": 6379,
"dbIndex": 0,
"password": "jianan"
},
"pubsub": {
"serverHost": "127.0.0.1",
"serverPort": 6379,
"dbIndex": 0,
"password": "jianan"
}
}
}
ConfigReaderUtils.java
package org.example;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URL;
import java.util.stream.Collectors;
public class ConfigReaderUtils {
public static JSONObject readResourcesConfig(String filePath) {
URL url = ConfigReaderUtils.class.getClassLoader().getResource(filePath);
try (BufferedReader br = new BufferedReader(new FileReader(url.getFile()))) {
String jsonText = br.lines().collect(Collectors.joining());
return JSONObject.parseObject(jsonText);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Main.java
package org.example;
import com.alibaba.fastjson.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject jsonObject = ConfigReaderUtils.readResourcesConfig("config.json");
System.out.println(jsonObject.get("redisXuite"));
}
}
/*
{"cache":{"password":"jianan","dbIndex":0,"serverPort":6379,"serverHost":"127.0.0.1"},"pubsub":{"password":"jianan","dbIndex":0,"serverPort":6379,"serverHost":"127.0.0.1"}}
*/
方式2: // 放到任意一个conf目录下即可,如:开机飞机
public static String getAsciiMessage(String messageName) {
String filePath = AsciiArt.class.getResource("/").getPath() + "ascii/" + messageName + ".txt";
return readFileToString(filePath);
}
public static String readFileToString(String filePath) {
String encoding = "ISO-8859-1";
File file = new File(filePath);
long fileLength = file.length();
byte[] fileContent = new byte[(int) fileLength];
try {
FileInputStream in = new FileInputStream(file);
in.read(fileContent);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
return new String(fileContent, encoding);
} catch (UnsupportedEncodingException e) {
System.err.println("The OS does not support " + encoding);
e.printStackTrace();
return "";
}
}