按指定的編碼讀取文本文件內(nèi)容

字號(hào):

InputStreamReader 的構(gòu)造函數(shù)提供了一個(gè)參數(shù),用于指定通過什么編碼將讀取到的字節(jié)流轉(zhuǎn)換成字符。下面是一個(gè)例子:
    /**
    *讀取指定的文本文件,并返回內(nèi)容
    *
    *@parampath文件路徑
    *@paramcharset文件編碼
    *
    *@return文件內(nèi)容
    *
    *@throwsIOException如果文件不存在、打開失敗或讀取失敗
    */
    privatestaticStringreadFile(Stringpath,Stringcharset)throwsIOException{
    Stringcontent="";
    BufferedReaderreader=null;
    try{
    reader=newBufferedReader(newInputStreamReader(newFileInputStream(path),charset));
    Stringline;
    while((line=reader.readLine())!=null){
    content+=line+"n";
    }
    }finally{
    if(reader!=null){
    try{
    reader.close();
    }catch(IOExceptione){
    //關(guān)閉Reader出現(xiàn)的異常一般不需要處理。
    }
    }
    }
    returncontent;
    }
    PS : 這只是一個(gè) InputStreamReader 的用法示例。真的碰到大文件,怎么可能都讀到內(nèi)存里面來?StringBuffer 都免了。