java操作属性文件

来源:互联网 发布:网络故障诊断 目的意义 编辑:程序博客网 时间:2024/05/29 17:10

一.在工程中,我们会发现有大量的以properties为后缀的文件,这些文件被称为属性文件。属性文件利于后期修改,不会破坏程序内部结构。属性文件是HashTable的子类,以键值对的形式出现。下面就来看一下对属性文件的操作。
读取属性文件
public void load(InputStream inStream) throws IOException {}
写属性文件
public void store(OutputStream out, String comments) throws IOException {}
首先,我们新建一个属性文件:

jdbc.driver=oracle.jdbc.driver.OracleDriver;jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:ORCL;jdbc.username=SCOTT;jdbc.password=cong960227;`

**注意:属性文件的分号是属于字符串,这里我一开始把他当做java语句,导致数据库链接出错,当然大家一般都不会犯这种错误,因为在java中字符串是这样定义的String str=”kobe”;
要读取属性文件,我们需要将test.properties以流的形式读取到Property对象中,然后读取其中的属性。

public class PropertiesUtil {    public static Properties getProperties(String file) {        Properties prop = new Properties();        FileInputStream in = null;        try {            in = new FileInputStream(file);            prop.load(in);        } catch (IOException e) {            // TODO: handle exception            if (e instanceof FileNotFoundException) {                System.out.println("找不到指定路径");            } else {                System.out.println("属性文件加载错误");            }        } finally {            try {                in.close();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        return prop;    }}

我们测试一下

public class PropertiesTest {    public static void main(String[] args) {        Properties prop = PropertiesUtil.getProperties("src/test.properties");        System.out.println("driver:" + prop.getProperty("jdbc.driver"));        System.out.println("url:" + prop.getProperty("jdbc.url"));    }}

这里写图片描述

0 0