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(); } } }