讀寫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,然後逐個位元組進行解析。