栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

铂西学习日记---Properties工具类

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

铂西学习日记---Properties工具类

假如有一些固定的属性像版本号,ip地址号,我想修改其中的属性,但是项目一旦发布后就得从第一步开始修改,每次都得经历编写-->打包-->发布的过程,很麻烦,配置文件很好的解决这个问题。

package io_12_properties;

import java.io.*;
import java.util.Properties;


public class demo {
    public static String version = "";
    public static String name = "";
    public static String pwd = "";
    //静态代码块,只执行一次,先执行
//    static {
//        readConfig();
//    }
    
    public static void readConfig(){
        Properties properties = new Properties();
        try {
            //如果想将配置文件放到指定的文件中---通过当前线程的类加载器来加载指定包下的配置文件
//            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("io_12_properties/test.properties");
            InputStream inputStream = new FileInputStream("test.properties");
            properties.load(inputStream);
            //从Properties中获取数据
            version = properties.getProperty("app.version");
            name = properties.getProperty("db.name");
            pwd = properties.getProperty("db.pwd");
            //关闭流
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
    public static void writeConfig(String version ,String name, String pwd){
        Properties properties = new Properties();
        properties.put("app.version",version);
        properties.put("db.name",name);
        properties.put("db.pwd",pwd);

        //写入
        try {
            OutputStream outputStream = new FileOutputStream("test.properties");

            //写文件--第二个参数为描述
            properties.store(outputStream,"update value!");
            //关闭流
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
    public static void clear(){
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("test.properties");
            properties.load(inputStream);
            properties.clear();
            OutputStream outputStream = new FileOutputStream("test.properties");
            properties.store(outputStream,"");
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //测试
    public static void main(String[] args) {
        //写
//        writeConfig("2.0","lsq666","666666");
        //读
        readConfig();
        System.out.println(demo.version);
        System.out.println(demo.name);
        System.out.println(demo.pwd);
        clear();

    }
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/729504.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号