Java讀寫Properties檔案及JavaIO中位元組流和字元的轉換

來源:互聯網
上載者:User
讀寫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,然後逐個位元組進行解析。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.