Java 小例子:按指定的编码读取文本文件内容

来源:互联网 发布:网络聊天技巧知乎 编辑:程序博客网 时间:2024/06/08 02:34

InputStreamReader 的构造函数提供了一个参数,用于指定通过什么编码将读取到的字节流转换成字符。下面是一个例子:

  1. /** 
  2.  * 读取指定的文本文件,并返回内容 
  3.  * 
  4.  * @param path    文件路径 
  5.  * @param charset 文件编码 
  6.  * 
  7.  * @return 文件内容 
  8.  * 
  9.  * @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 都免了。