文章目录
转换流
一、概念
提供字节流与字符流之间的转换。
二、分类
- InputStreamReader:将一个字节的输入流转换为字符的输入流(解码)
- OutputStreamWriter :将一个字符的输出流转换为字节的输出流(编码)
三、示例
(一)InputStreamReader
@Test
public void test() {
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
try {
fileInputStream = new FileInputStream("hello.txt");
//将字节转为字符,可以设置字符编码
inputStreamReader = new InputStreamReader(fileInputStream, "utf-8");
char[] cbuf = new char[10];
int len;
while ((len = inputStreamReader.read(cbuf)) != -1) {
for (int i = 0; i < len; i++) {
System.out.print(cbuf[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(二)综合
@Test
public void test2() {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
InputStreamReader inputStreamReader = null;
OutputStreamWriter outputStreamWriter = null;
try {
//1、创建文件对象
File hello = new File("hello.txt");
File hi = new File("hi.txt");
//2、创建输入输出流对象
fileInputStream = new FileInputStream(hello);
fileOutputStream = new FileOutputStream(hi);
//3、创建转换流
inputStreamReader = new InputStreamReader(fileInputStream);
outputStreamWriter = new OutputStreamWriter(fileOutputStream,"gbk");//以gbk的方式写入字节
//4、读取、写入
char[] cbuffer = new char[20];
int len;
while ((len = inputStreamReader.read(cbuffer)) != -1) {
outputStreamWriter.write(cbuffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//5、关闭流
if(outputStreamWriter != null){
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStreamReader != null){
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}