java按字元讀取txt文件
/**
* 以字元為單位讀取檔案,常用於讀文字,數字等型別的檔案
*/
public static String readTxtFile(String CURENO) { String url = resultfilePath + CURENO + ".txt"; //檔案路徑 File file = new File(url); Reader reader = null; StringBuffer buffer = new StringBuffer(); try {
//一次讀一個字元 reader = new InputStreamReader(new FileInputStream(file)); int tempchar; try { while((tempchar = reader.read())!=-1) {
// 對於windows下,\r\n這兩個字元在一起時,表示一個換行。
// 但如果這兩個字元分開顯示時,會換兩次行。
// 因此,遮蔽掉\r,或者遮蔽\n。否則,將會多出很多空行。
if(((char)tempchar)!='\r') { buffer.append((char)tempchar); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }catch(FileNotFoundException e) { e.printStackTrace(); } try {
//一次讀多個字元 char[] tempchars = new char[30]; int charread = 0; reader = new InputStreamReader(new FileInputStream(file));
// 讀入多個字元到字元陣列中,charread為一次讀取字元數
while((charread = reader.read(tempchars))!=-1) {
// 同樣遮蔽掉\r不顯示
if((charread == tempchars.length)&&(tempchars[tempchars.length-1]!='\r')) { buffer.append(tempchars); }else { for(int i = 0;i < charread;i++) { if(tempchars[i] == '\r') { continue; }else { buffer.append(tempchars[i]); } } } } }catch(Exception e1) { e1.printStackTrace(); }finally { if (reader != null) try { reader.close(); }catch(IOException e1) { } }
return buffer.toString(); }