Java小例子:按指定的編碼讀取文字檔內容

來源:互聯網
上載者:User

InputStreamReader 的建構函式提供了一個參數,用於指定通過什麼編碼將 讀取到的位元組流轉換成字元。下面是一個例子:

01./**02. * 讀取指定的文字檔,並返回內容03. *04. * @param path    檔案路徑05. * @param charset 檔案編碼06. *07. * @return 檔案內容08. *09. * @throws IOException 如果檔案不存在、開啟失敗或讀取失敗10. */11.private static String readFile(String path, String charset) throws IOException {12.    String content = "";13.    BufferedReader reader = null;14.    try {15.        reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), charset));16.        String line;17.        while ((line = reader.readLine()) != null) {18.            content += line + "\n";19.        }20.    } finally {21.        if (reader != null) {22.            try {23.                reader.close();24.            } catch (IOException e) {25.                // 關閉 Reader 出現的異常一般不需要處理。26.            }27.        }28.    }29.    return content;30.}

PS : 這隻是一個 InputStreamReader 的用法樣本。真的碰到大檔案,怎麼 可能都讀到記憶體裡面來?StringBuffer 都免了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.