java 高并发读取txt项目配置文件_工具类:Java从项目可执行jar同级目录读取配置文件工具类...

有时候,我们在编写java程序的时候,都是把一些可配置的新的写到配置文件里,但是不能跟项目一起打包,因为配置文件可能会需要经常修改,所以最好能在同级目录。

项目结构如下
78b888306cdb3b7d80f6df21d7a8da5b.png

可以看到,app.properties在同级目录下,打包为可执行jar过后,jar包里面没有app.properties文件,放到了外面,然后就可以轻松修改了。

工具类
/** * 用完美的单例模式获取properties的数据,加载为map * @author forever * */public class PropertiesUtil {    //值可变,引用不可变    private static final Properties PROPERTIES =new Properties();    static{        initProperties();    }    /**     * @param key     * @param defaultValue     * @return     */    public static String get(String key,String defaultValue){        if(PROPERTIES.isEmpty()) {            throw new UnsupportedOperationException("配置未加载");        }        String value =PROPERTIES.getProperty(key, defaultValue);        return  value;    }    /**     * 获取默认配置的值,这个值可以动态修改     * @param key     * @return     */    public static String get(String key){        return get(key, "");    }    private static void initProperties(){         InputStream is =null;         try {             //获取当前目录             String property = System.getProperty("user.dir");             //默认是linux os             String fileName = "/app.properties";             //判断是否是windows os             if(System.getProperty ("os.name").contains("Windows")) {                 fileName = "app.properties";             }             // 读取当前目录下conf配置文件             File file = new File(property+fileName);             PROPERTIES.clear();             is = new FileInputStream(file);             PROPERTIES.load(is);         }catch (IOException e) {              e.printStackTrace();         }finally {            if(is!=null) {                try {                    is.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }         }    }    public static void main(String[] args) {        System.out.println(PropertiesUtil.get("name"));    }}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值