处理流_转换流(字符流)
/**
* 处理六:转换流的使用
* 1.转换流:属于字符流
* InputStreamReader:将一个字节的输入流转换为字符的输入流
* OutputStreamWriter:将一个字符的输出流转换为字节的输出流
*
* 2.作用:提供字符与字节之间的转换
* 3.解码:字节、数组 ---》 字符、字符串 InputStreamReader
* 编码:字符、字符串 ---》 字节、数组 OutputStreamWriter
*
* 4.字符集
*/
public class IOStreamReaderAndWriter {
public static void main(String[] args) {
InputStreamReader inputStreamReader = null;
try {
FileInputStream fileInputStream = new FileInputStream("基础语法\\a.txt");
// InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);//使用系默认的字符集 UTF-8
//使用utf-8 取决于原来保存时的字符集
inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
char[] cbuf = new char[20];
int len;
while ((len = inputStreamReader.read(cbuf)) != -1){
String string = new String(cbuf,0,len);
System.out.println(string);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStreamReader != null)
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OutputStreamWriter:将Writer转换为OutputStream
/**
* 处理六:转换流的使用
* 1.转换流:属于字符流
* InputStreamReader:将一个字节的输入流转换为字符的输入流
* OutputStreamWriter:将一个字符的输出流转换为字节的输出流
*
* 2.作用:提供字符与字节之间的转换
* 3.解码:字节、数组 ---》 字符、字符串 InputStreamReader
* 编码:字符、字符串 ---》 字节、数组 OutputStreamWriter
*
* 4.字符集
*
*/
public class IOStreamReaderAndWriter {
public static void main(String[] args) {
InputStreamReader inputStreamReader = null;
OutputStreamWriter outputStreamWriter = null;
try {
/*
综合使用InputStreamReader和OutputStreamWriter 实现文本文件字符集的转换
*/
//造文件 、造流
File file1 = new File("基础语法\\a.txt");
File file2 = new File("基础语法\\gbk_a.txt");
FileInputStream fileInputStream = new FileInputStream(file1);
FileOutputStream fileOutputStream = new FileOutputStream(file2);
inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
outputStreamWriter = new OutputStreamWriter(fileOutputStream,"gbk");
//读写过程
char[] cbuf = new char[20];
int len;
while ((len = inputStreamReader.read(cbuf)) != -1){
outputStreamWriter.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
try {
if (inputStreamReader != null)
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (outputStreamWriter != null)
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}