InputStreamReader和OutputStreamWriter常用方法详解
InputStreamReader和OutputStreamWriter是字符流,InputStreamReader继承自Reader类,因此Reader字符流常用的方法它都有,OutputStreamWriter继承自Writer类,因此Writer字符流常用的方法它都有,InputStreamReader和OutputStreamWriter常用的功能是做转换流,将InputStream字节流转换成Reader字符流,进而包装成BufferedReader流,将OuterputStreamWriter字节流转换成Writer字符流,进而包装成BufferedWriter流
InputStreamReader
InputStreamReader构造器
有以下几种常用的构造器
-
public InputStreamReader(InputStream in)
可以传入InputStream或其子类对象,使用默认字符编码UTF-8
-
public InputStreamReader(InputStream in, String charsetName)
可以传入InputStream或其子类对象,通过传入字符编码对应的String字符串来指定转换字符编码
1 |
|
1 |
|
转换成BufferedReader
1 |
|
OutputStreamWriter
OutputStreamWriter构造器
有以下几种常用的构造器
-
public OutputStreamWriter(OutputStream out
可以传入OutputStream或其子类对象,使用默认字符编码UTF-8
-
public OutputStreamWriter(OutputStream out, String charsetName)
可以传入OutputStream或其子类对象,通过传入字符编码对应的String字符串来指定转换字符编码
1 |
|
1 |
|
转换成BufferedWriter
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(Files.newOutputStream(Paths.get("news.txt")), "UTF-8");
// 转换成BufferedWriter
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);