转换流
在正常情况下,字节流可以对所有数据进行操作,但是有些时候在处理一些文本时我们要用到字符流,比如,查看文本时采用字符流更为方便,而在使用字节流时,当遇到中文及一些特殊字符时,就会出现乱码的情况,这是因为在UTF-8的字符编码下,中文占有3个字节。因此通常当我们在读取文本文件时,会选择使用字符流来处理。
除了使用字符流来读写文本文件时,我们还可以使用转换流,将字节流转换为字符流,从而解决中文UTF-8编码下的乱码问题。
所以 IO 流中提供了两种用于将字节流转换为字符流的转换流。
InputStreamReader
用于将字节输入流转换为字符输入流。OutputStreamWriter
用于将字节输出流转换为字符输出流。
InputStreamReader
InputStreamReader
类用于将字节输入流转换为字符输入流。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK。
InputStreamReader
类可与其它输入流一起使用。它被称为字节流和字符流之间的桥梁。
try (
FileInputStream fileInputStream = new FileInputStream("test.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream)
) {
int tmp;
while ((tmp = inputStreamReader.read()) != -1) {
System.out.print((char) tmp);
}
} catch (IOException e) {
System.out.println("文件读取失败");
}
键盘输入流转换为字符流
try (
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
) {
String line = null;
while ((line = bufferedReader.readLine()) != null) {
// 如果读取的字符串为“exit”,则程序退出
if (line.equals("exit")) {
System.exit(1);
}
// 打印读取的内容
System.out.println("输入内容为:" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
OutputStreamWriter
OutputStreamWriter
类用于将字符形式的数据转换为字节形式的数据。是字符流通向字节流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK。
try (
FileOutputStream fileOutputStream = new FileOutputStream("output.txt");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8)
) {
outputStreamWriter.write("hello word");
} catch (IOException e) {
e.printStackTrace();
}
try (
FileInputStream fileInputStream = new FileInputStream("input.txt");
FileOutputStream fileOutputStream = new FileOutputStream("output.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)
) {
int tmp;
while ((tmp = bufferedReader.read()) != -1) {
System.out.println((char) tmp);
bufferedWriter.write(tmp);
}
} catch (IOException e) {
e.printStackTrace();
}
最后更新于
这有帮助吗?