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 都免了。