java读取jar包内置文件或同目录下配置文件

java读取jar包内置文件或同目录下配置文件

读取jar包同目录下文件

java程序在打成jar包后,jar内的文件就不再具备文件系统级别的路径,因此要读取jar包同目录下的文件,就需要特殊处理

这里使用properties文件举例。

/**
 *
 * @param fileName 打成jar后同目录下的文件名 例:config.properties
 * @return
 */
public static Properties loadProperties(String fileName) {
    URL url = PropertiesUtil.class.getResource("/");
    if(url==null){
        url = PropertiesUtil.class.getResource("");
    }
    // 执行后url为 jar:file:/D:/auth/myapp.jar!/com/abc/test/rpa/tools/

    String str = url.getPath();
    // str为 file:/D:/auth/myapp.jar!/com/abc/test/rpa/tools/

    int i2 = str.indexOf("/"); //第一个/的位置
    int i = str.indexOf(".jar!");
    if(i>0){
        str = str.substring(i2+1, i);
    }
    // str为 D:/auth/myapp

    int i3 = str.lastIndexOf("/");
    str = str.substring(0,i3+1);
    // str为 D:/auth/

    int i1 = str.indexOf(":");
    if(i1==-1){
        str = "/"+str;
    }

    //获取到jar运行的系统中的绝对路径

    Properties properties = new Properties();
    // 使用InPutStream流读取properties文件
    BufferedReader bufferedReader = null;
    try {
        InputStreamReader isr = new InputStreamReader(new FileInputStream(str + fileName), "UTF-8");
        bufferedReader = new BufferedReader(isr);
        properties.load(bufferedReader);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return properties;
}

若使用json配置,也可以使用readLine方法,然后再将每一行拼接成完整字符串。


String s="";
String configContentStr = "";
while((s=bufferedReader.readLine())!=null) {
    configContentStr = configContentStr+s;
}
// 解析成json对应实体
JSONConfig jsonConfig = JSONObject.parseObject(configContentStr, JSONConfig.class);

读取jar包内置文件

当前工程resources文件夹下的有一个config文件夹,config中有一个config.json配置文件

private static JSONConfig getJsonConfig() throws UnsupportedEncodingException {
    InputStream is = 当前类名.class.getResourceAsStream("/config/config.json");
    BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
    String s="";
    String configContentStr = "";
    try {
        while((s=br.readLine())!=null) {
            configContentStr = configContentStr+s;
        }
    } catch (IOException e) {

        e.printStackTrace();
    }

    JSONConfig jsonConfig = JSONObject.parseObject(configContentStr, JSONConfig.class);

    return jsonConfig;
}

两种文件读取都尽量不要使用FileReader,虽然FileReader方便,但是FileReader不支持指定编码。如果文件中存在中文字符,java在使用FileReader读取时,就会使用默认编码方式UTF-16,导致乱码出现。

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值