InputStreamReader、OutputStreamReader转换流的使用
转换流:属于字符流
InputStreamReader :将一个字节的输入转化为字符的输入流 OutputStreamReader : 将一个字符的输入转化为字节的输入流
作用:提供字节流和字节流主之间的转换 编码:字节、字节数组转化为字符数组字符串 解码:字符数组、字符串转化为字节、字节数组
public classInputStreamReaderTest{
@Test
public void test ( ) {
FileInputStream fis = new FileInputStream ( "hello.txt" ) ;
InputStreamReader isr = new InputStreamReader ( fis, "UTF-8" ) ;
char [ ] buf = new char [ 20 ] ;
int len;
while ( ( len = isr. read ( buf) ) != - 1 ) {
String str = new String ( buf, 0 , len) ;
System. out. println ( str) ;
}
isr. close ( ) ;
}
}
转化文件的字符集
@Test
public void test ( ) throws IOException{
File file1 = new File ( "hello1" ) ;
File file2 = new File ( "hello1" ) ;
FileInputStream fis = new FileInputStream ( file1) ;
FileOutputStream fos = new FileOutputStream ( file2) ;
InputStreamReader isr = new InputStreamReader ( fis, "UTF-8" ) ;
OutPutStreamWriter osw = new OutPutStreamWriter ( osw, "gbk" ) ;
char [ ] cbuf = new char [ 20 ] ;
int lenth= 0 ;
while ( ( lenth = isr. read ( buf) ) != - 1 ) {
osw. write ( cbuf, 0 , len) ;
}
isr. close ( ) ;
osw. close ( ) ;
}
为了便于阅读将异常抛出,实际开发使用try catch finally 确保资源得到关闭。
字符集
ASCII:美国标准信息交换码,用一个字节的7位可以表示 ISO8859-1:拉丁码表,欧洲码表,用一个字节的8位表示 GB2313:中国的中文编码表,最多两个字节编码所有字符 GBK:中国的中文编码表升级,融合了更多的中文文字符号,最多两个字节编码 Unicode:国际标准编码,融合了目前人类使用对的所有字符,为每个字符分配唯一的字符码,所有的文字都用两个字节表示 UTF-8:变长的编码方式,可用1-4个字节来表示一个字符