InputStreamReader是Reader的最重要的具體字子類。InputStreamReader從其底層輸入流(如FileInputStream或TelnetInputStream)中讀取字節。它根據指定的編碼方式將這些字節轉換爲字符,並返回這些字符。構造函數指定要讀取的輸入流和所用的編碼方式:java
public InputStreamReader(InputStream in) public InputStreamReader(InputStream in,String encoding) throws UnsupportedEncodingException
若是沒有指定編碼方式,就使用平臺的默認編碼方式。若是指定了一個未知的編碼方式,會拋出UnsupportedEncodingException異常。咱們來看下面這個例子:app
package io; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class InputStreamReaderTest { public static void main(String[] args) { try(InputStreamReader reader = new InputStreamReader( new BufferedInputStream(new FileInputStream( new File("/home/fuhd/text"))),"UTF-8")){ int c; StringBuffer sb = new StringBuffer(); while((c = reader.read()) != -1){ sb.append((char)c); } System.out.println(sb.toString()); }catch(IOException e){ e.printStackTrace(); } } }