1.读取resources下的config.json配置文件 2.使用FileInputstream读取conf下的

方式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 "";
        }
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值