Java读写Properties文件及JavaIO中字节流和字符的转换

来源:互联网 发布:c语言程序头文件 编辑:程序博客网 时间:2024/05/17 02:13

读写properties文件

Java读写Properties文件是一个比较常见的需求,一般的做法是将properties文件读到Properties类对象中,通过Properteis对象来操作。下面是一段实例代码:

    /**     * Read Properties file with ASCII codes only     */ public static Properties getProperties(String fileName, String path){    Properties props = new Properties();        InputStream in = null;try {in = new FileInputStream(path + fileName);} catch (FileNotFoundException e1) {System.out.println("Can't find c3p0.properties");}    try {props.load(in);in.close();} catch (IOException e) {System.out.println("Can't load c3p0.properties");}       return props;    }
上面的代码是用于读取仅包含ASCII码的properties文件,特点是只用了FileInputStream,而没有像往常一样在外面套个FileReader。下面的代码用于写ASCII编码的properties文件:

    /**     *      */    private void setPassword(String passWord){    Properties props = DBUtil.getC3P0Properties();    FileOutputStream out;try {String path = DBUtil.getFullPath(this.getClass());out = new FileOutputStream(path + "/c3p0.properties" );            props.setProperty("c3p0.password", passWord);            props.store(out, "Prevent connect for failed connection");            out.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}    }

字节流到字符的转换

关于Java I/O的更全面信息,可以参考Developerworks上的这篇文章:http://www.ibm.com/developerworks/cn/java/j-lo-javaio/

这里贴一下StreamDecoder中的核心方法,看看StreamDecoder是怎样将Stream转为Character的吧:

  private int read0() throws IOException {        synchronized (lock) {            // Return the leftover char, if there is one            if (haveLeftoverChar) {                haveLeftoverChar = false;                return leftoverChar;            }            // Convert more bytes            char cb[] = new char[2];            int n = read(cb, 0, 2);            switch (n) {            case -1:                return -1;            case 2:                leftoverChar = cb[1];                haveLeftoverChar = true;                // FALL THROUGH            case 1:                return cb[0];            default:                assert false : n;                return -1;            }        }    }

从上面的代码可以看出,StreamDecoder每次读入两个byte,然后逐个字节进行解析。

原创粉丝点击