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,导致乱码出现。

经验分享 程序员 微信小程序 职场和发展