读取.Properties配置文件

方法一,读取.txt文件

package _10Properties类;

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

//Properties
// 使用记事本写配置文件
// 程序来读

public class PropertiesDemo {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        // TODO Auto-generated method stub

        
//        testWrite();
        
        testRead();
    }

    private static void testWrite() throws FileNotFoundException, IOException {
        // TODO Auto-generated method stub
        // 1. 创建
        Properties p = new Properties();
        // 2. 设置
        p.put("admin", "qinag");
        p.put("pass","123123");
        // 3. 写入到文件
        p.store(new FileOutputStream("e:\\igeek\\setting2.txt"), null);
        
    }

    private static void testRead() throws FileNotFoundException, IOException {
        // TODO Auto-generated method stub
        
        
        // 1. 创建
        Properties p = new Properties();
        // 2. 载入配置文件
        p.load(new FileInputStream("e:\\igeek\\settings.txt"));
        // 3. 获取信息
        System.out.println("用户名:"+p.getProperty("username"));
        System.out.println("密码:"+p.getProperty("password"));
        
    }

}

 

方法二读取.properties文件

package com.st.common;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.st.common.prop.PropertiesProviderFactory;

/**
 * 读取后缀名为“.properties”的文件 
 * @author
 *
 */
public class SystemConfig
{

    private static final String CONFIG_PROPERTIES = "conf/config.properties";

    public static String getConfigResource(String key) throws Exception
    {
      /*  ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Properties properties = new Properties();
        InputStream in = loader.getResourceAsStream(CONFIG_PROPERTIES);
        properties.load(in);
        String value = properties.getProperty(key);
        // 编码转换,从ISO-8859-1转向指定编码  
        value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
        in.close();*/
        
        String value = (String) PropertiesProviderFactory
        .getDefaultPropertiesProvider().getKeyValue(key);
        // 编码转换,从ISO-8859-1转向指定编码  
        value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
        return value;
    }
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_无往而不胜_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值