import org.junit.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* 处理流之二:转换流
*
* 1.InputStreamReader\OutputStreamWriter(看后缀:字符流)
* 2.读写使用char数组
* 3.作用:提供字节流与字符流之间的转换
* InputStreamReader:将一个字节输入流转换为字符输入流
* OutputStreamWriter:将一个字符输出流转换为字节流
*
* 3.字节、字节数组 --->字符数组、字符串(解码)
* 字符数组、字符串 --->字节、字节数组 (编码)
*
* 4.字符集
*
*
* @author orz
*/
public class IOStreamReaderWriter {
@Test
public void test()throws IOException
{
InputStreamReader isr;
OutputStreamWriter osw;
File file1=new File("hello.txt");
FileInputStream fis=new FileInputStream(file1);
//参数2指明了字符集,具体使用哪个字符集取决于文件保存时使用的字符集
// isr=new InputStreamReader(fis, StandardCharsets.UTF_8);
isr=new InputStreamReader(fis);
// isr=new InputStreamReader(fis, "GBK");
char [] cbuf=new char[1024];
int len;
while ((len=isr.read(cbuf))!=-1)
{
String str=new String(cbuf,0,len);
System.out.print(str);
}
isr.close();
//osw.close();
}
/**
*
* 综合使用
*/
@Test
public void test2()throws IOException
{
InputStreamReader isr;
OutputStreamWriter osw;
File file1=new File("hello.txt");
File file2=new File("hi.txt");
FileInputStream fis=new FileInputStream(file1);
FileOutputStream fos=new FileOutputStream(file2);
//参数2指明了字符集,具体使用哪个字符集取决于文件保存时使用的字符集
isr=new InputStreamReader(fis,"utf-8");
//isr=new InputStreamReader(fis);
// isr=new InputStreamReader(fis, "GBK");
osw=new OutputStreamWriter(fos,"gbk");
char [] cbuf=new char[1024];
int len;
while ((len=isr.read(cbuf))!=-1)
{
osw.write(cbuf,0,len);
}
isr.close();
osw.close();
}
}