方法一,读取.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;
}
}