字符流
字节流操作中文数据不是特别的方便,所以就出现了转换流。转换流的作用就是把字节流转换字符流来使用。
转换流其实是一个字符流
字符流 = 字节流 + 编码表
编码表
A:就是由字符和对应的数值组成的一张表
B:常见的编码表 ASCII
ISO-8859-1 GB2312 GBK GB18030 UTF-8
C:字符串中的编码问题编码
String -- byte[]
解码
byte[] -- String
IO 流中的编码问题
A:OutputStreamWriter
OutputStreamWriter(OutputStream os): 默 认 编 码 , GBK OutputStreamWriter(OutputStream os,String charsetName): 指定编码。
B:InputStreamReader
InputStreamReader(InputStream is): 默 认 编 码 , GBK InputStreamReader(InputStream is,String charsetName): 指定编码
C:编码问题其实很简单编码只要一致即可
字符流
Reader
|--InputStreamReader
|--FileReader
|--BufferedReader
Writer
|--OutputStreamWriter
|--FileWriter
|--BufferedWriter
案例:复制文本文件 (5 种方式 )
// 基本字符流一次读写一个字符
privatestaticvoid method1(String srcString, String destString) throws IOException {
FileReader fr = newFileReader(srcString);
FileWriter fw = newFileWriter(destString);
int ch = 0;
while ((ch = fr.read()) != -1) { fw.write(ch);
}
fw.close();
fr.close();
}
// 基本字符流一次读写一个字符数组
privatestaticvoid method2(String srcString, String destString) throws IOException {
FileReader fr = newFileReader(srcString); FileWriter fw = newFileWriter(destString);
char [] chs = newchar [1024]; int len = 0;
while ((len = fr.read(chs)) != -1) { fw.write(chs, 0, len);
}
fw.close();
fr.close();
}
// 字符缓冲流一次读写一个字符
privatestaticvoid method3(String srcString, String destString) throws IOException {
BufferedReader br = newBufferedReader(newFileReader(srcString));
BufferedWriter bw = newBufferedWriter(newFileWriter(destString));
int ch = 0;
while ((ch = br.read()) != -1) { bw.write(ch);
}
bw.close();
br.close();
}
// 字符缓冲流一次读写一个字符数组
privatestaticvoid method4(String srcString, String destString) throws IOException {
BufferedReader br = newFileReader(srcString));
newBufferedReader(newFileWriter(destString));
char [] chs = newchar [1024];
int len = 0;
while ((len = br.read(chs)) != -1) {
bw.write(chs, 0, len);
}
bw.close();
br.close();
}
// 字符缓冲流一次读写一个字符串
privatestaticvoid method5(String srcString, String destString) throws IOException {
BufferedReader br = newFileReader(srcString));
newBufferedReader(newFileWriter(destString));
String line = null;
while ((line = br.readLine()) != null) { bw.write(line);
bw.newLine();
bw.flush();
}