配置文件读取

来源:互联网 发布:2345网络电视直播 编辑:程序博客网 时间:2024/05/18 19:21

前言:项目中某些属性是通过配置文件配置的,然后读取配置文件来获取这些属性,通常都是通过配置.properties文件来设置属性。但事实上,我们可以配置任意格式的文件来配置属性,然后读取,并不局限于.properties文件。只要文件内容的格式符合key-value这样的即可读取,例如:url=csdn.com(url是key,csdn.com是value)。代码如下:

/** * 文件名:ReadProperties.java<br/> * 创建时间:2015-7-29 下午03:11:14<br/> * 创建者:Administrator<br/> * 修改者:暂无<br/> * 修改简述:暂无<br/> * 修改详述: * <p> * 暂无<br/> * </p> * 修改时间:暂无<br/> */package hui.sample.properties.test;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Properties;/** * TODO 读取属性配置文件<br/> * <p> * TODO 读取和操作属性配置文件,不限于.properties文件,只需求文件内容是key-value形式(如url=pdm.8602.com)<br/> * </p> * Time:2015-7-29 下午03:11:14<br/> * @author Administrator * @version 1.0.0 * @since 1.0.0 */public class ReadProperties {public static Properties getProperties(String filePath) throws FileNotFoundException, IOException{Properties properties = null;File file = new File(filePath);if (file.exists() && file.isFile()) {properties = new Properties();properties.load(new FileInputStream(file));//文件输入流load到properties对象}else {System.out.println("文件'"+file.getAbsolutePath()+"'不存在");}return properties;}public static String getValue(String filePath,String key) throws FileNotFoundException, IOException{Properties properties = getProperties(filePath);String value = properties.getProperty(key);//通过key获取value值<span style="color:#ff0000;">String localEN = System.getProperty("file.encoding");//获取本地文件编码if (value != null && value != "") {value = new String(value.getBytes("ISO-8859-1"), localEN);//进行编码转换,防止乱码}</span>return value;}public static void main(String[] args) {String filePath = "D:\\test.txt";//用txt文件测试String key = "test";try {System.out.println("======"+getValue(filePath, key));} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}


0 0
原创粉丝点击