• java jar包与配置文件的写法


    一个普通的java project,里面引用了config.properties配置文件,将项目打成Runnable jar,然后将config.properties放到打包后的jar路径下,执行该jar包,出错,原工程中properties文件读取代码如下:

     InputStream in = SystemConfig.class.getResourceAsStream("/config.properties");
     FileInputStream in = new FileInputStream(rootPath+"/config.properties");

         上网搜了下class.getResource方式读取配置文件时,在eclipse中运行是没有问题的。将该类打包成jar包执行,如果配置文件没有一起打包到该jar包中,文件查找的路径就会报错。但是对于配置文件,我们一般不希望将其打包到jar包中,而是一般放到jar包外,随时进行配置。修改方式如下:

    String rootPath = System.getProperty("user.dir").replace("\", "/");
    FileInputStream in = new FileInputStream(rootPath+"/config.properties");

         首先程序获取程序的执行路径,也就是你打包后的jar存放路径,然后找到该路径下的config.properties文件读取,就可以了。

    String rootPath = System.getProperty("user.dir").replace("\", "/");
    FileInputStream in = new FileInputStream(rootPath+File.separator+"kafkaSinkConfig.properties");
     
    package my.utils;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Properties;

    /**
    * Created by lq on 2017/9/3.
    */
    public class PropertiesUtils {

    public static Properties getPropertiesFromUserDir(String propfile){
    Properties properties = new Properties();
    String rootPath = System.getProperty("user.dir");
    FileInputStream in = null;
    try {
    in = new FileInputStream(rootPath + File.separator + propfile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    }
    try {
    properties.load(in);
    } catch (IOException e) {
    e.printStackTrace();
    }
    try {
    in.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return properties;
    // TOPIC = (String) properties.get("topic");//
    }

    public static void main(String[] args) {
    System.out.println(getPropertiesFromUserDir("topic.cfg").stringPropertyNames());
    }
    }

    备注:对于其他的一些配置文件读取,也要相应修改,例如mybatis读取配置文件,默认方式是

    java.io.Reader reader = Resources.getResourceAsReader("Configuration.xml");
    factory = new SqlSessionFactoryBuilder().build(reader);

    如果打包到jar运行,Configuration.xml没有打包进去,也会报错,统一修改成

    复制代码
    String rootPath = System.getProperty("user.dir").replace("\", "/");
    java.io.Reader reader = new FileReader(rootPath+"/Configuration.xml");
    factory = new SqlSessionFactoryBuilder().build(reader);

    出自博客:http://www.cnblogs.com/king1302217/p/5434989.html
    复制代码
  • 相关阅读:
    解决chrome console打印的信息一闪而过
    Docker 构建自定义镜像
    Docker 镜像、容器、仓库
    Docker 简介、下载安装
    执行yum list installed | grep xxx 命令时报错:未提供依赖perl-DBD-SQLite、perl-DBI
    SpringBoot 配置多种运行环境
    SpringCloud Config 分布式配置管理
    SpringCloud Sleuth+Zipkin 分布式链路追踪
    Dubbo 配置中心、元数据中心
    dubbo admin的使用
  • 原文地址:https://www.cnblogs.com/rocky-AGE-24/p/7469066.html
Copyright © 2020-2023  润新知