• Java中Properties类的操作


    Java中Properties类的操作

     =============================================

    com.gordon.constant

    Constant.java:

    package com.gordon.constant;
    
    public interface Constant {
    	
    	/**
    	 * 根据名称读取常量
    	 * @param name
    	 * @return
    	 */
    	public String get_constant(String name);
    }
    

    SystemConstant4PropImpl.java

    package com.gordon.constant;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    public class SystemConstant4PropImpl implements Constant {
    
    	public Properties prop = null;
    
    	public SystemConstant4PropImpl() {
    		InputStream in = ClassLoader.getSystemResourceAsStream("constant.properties");
    		prop = new Properties();
    		try {
    			prop.load(in);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
    	public SystemConstant4PropImpl(String prop_path) {
    		InputStream in = ClassLoader.getSystemResourceAsStream(prop_path);
    		prop = new Properties();
    		try {
    			prop.load(in);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * 获取properties文件中的属性
    	 */
    	@Override
    	public String get_constant(String name) {
    		return prop.getProperty(name);
    	}
    }
    

    SystemConstant4XMLImpl.java

    package com.gordon.constant;
    
    public class SystemConstant4XMLImpl {
    	
    }
    

    com.grodon.test

    TestConstantClass.java:

    package com.gordon.test;
    
    import org.junit.Test;
    
    import com.gordon.constant.SystemConstant4PropImpl;
    
    public class TestConstantClass {
    	@Test
    	public void run() {
    		try {
    			SystemConstant4PropImpl scp = new SystemConstant4PropImpl();
    			String db_username = scp.get_constant("db.username");
    			System.out.println(db_username);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    constant.properties:

    db.username=root
    

    运行结果:

  • 相关阅读:
    UDP协议测试
    openstack ussusi ubuntu 20 centos8 dracut initqueue timeout
    wol linux远程通过数据帧自动开机
    openStack proformancee bottlenecks options optimized
    find 搜索排除搜索目录
    Ipv6
    golang学习笔记 ---日志库 logrus
    golang学习笔记---- 格式化IO
    golang学习笔记 --- struct 嵌套
    golang学习笔记---HTTPS
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/7611536.html
Copyright © 2020-2023  润新知