InputStreamReader和OutputStreamWriter是字符流,InputStreamReader继承自Reader类,因此Reader字符流常用的方法它都有,OutputStreamWriter继承自Writer类,因此Writer字符流常用的方法它都有,InputStreamReader和OutputStreamWriter常用的功能是做转换流,将InputStream字节流转换成Reader字符流,进而包装成BufferedReader流,将OuterputStreamWriter字节流转换成Writer字符流,进而包装成BufferedWriter流

InputStreamReader

InputStreamReader构造器

有以下几种常用的构造器

  1. public InputStreamReader(InputStream in)

    可以传入InputStream或其子类对象,使用默认字符编码UTF-8

  2. public InputStreamReader(InputStream in, String charsetName)

    可以传入InputStream或其子类对象,通过传入字符编码对应的String字符串来指定转换字符编码

1
2
// 构造1
InputStreamReader inputStreamReader = new InputStreamReader(Files.newInputStream(Paths.get("E:\\news.txt")));
1
2
3
// 构造2:指定字符编码
InputStreamReader inputStreamReader = new
InputStreamReader(Files.newInputStream(Paths.get("E:\\news.txt")), "UTF-8");

转换成BufferedReader

1
2
3
InputStreamReader inputStreamReader = new InputStreamReader(Files.newInputStream(Paths.get("E:\\news.txt")), "UTF-8");
// 转换成BufferedReader
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

OutputStreamWriter

OutputStreamWriter构造器

有以下几种常用的构造器

  1. public OutputStreamWriter(OutputStream out

    可以传入OutputStream或其子类对象,使用默认字符编码UTF-8

  2. public OutputStreamWriter(OutputStream out, String charsetName)

    可以传入OutputStream或其子类对象,通过传入字符编码对应的String字符串来指定转换字符编码

1
2
// 构造1
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(Files.newOutputStream(Paths.get("news.txt")));
1
2
// 构造2:指定字符编码
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(Files.newOutputStream(Paths.get("news.txt")), "UTF-8");

转换成BufferedWriter

OutputStreamWriter outputStreamWriter = new OutputStreamWriter(Files.newOutputStream(Paths.get("news.txt")), "UTF-8");
// 转换成BufferedWriter
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);