java io流相互转换_JavaIO流-转换流
importorg.junit.Test;import java.io.*;importjava.nio.charset.StandardCharsets;/*** 处理流之二:转换流
*
* 1.InputStreamReader\OutputStreamWriter(看后缀:字符流)
* 2.读写使用char数组
* 3.作用:提供字节流与字符流之间的转换
* InputStreamReader:将一个字节输入流转换为字符输入流
* OutputStreamWriter:将一个字符输出流转换为字节流
*
* 3.字节、字节数组 —->字符数组、字符串(解码)
* 字符数组、字符串 —->字节、字节数组 (编码)
*
* 4.字符集
*
*
*@authororz*/
public classIOStreamReaderWriter {
@Testpublic void test()throwsIOException
{
InputStreamReader isr;
OutputStreamWriter osw;
File file1=new File(“hello.txt”);
FileInputStream fis=newFileInputStream(file1);//参数2指明了字符集,具体使用哪个字符集取决于文件保存时使用的字符集//isr=new InputStreamReader(fis, StandardCharsets.UTF_8);
isr=newInputStreamReader(fis);//isr=new InputStreamReader(fis, “GBK”);
char [] cbuf=new char[1024];intlen;while ((len=isr.read(cbuf))!=-1)
{
String str=new String(cbuf,0,len);
System.out.print(str);
}
isr.close();//osw.close();
}/***
* 综合使用*/@Testpublic void test2()throwsIOException
{
InputStreamReader isr;
OutputStreamWriter osw;
File file1=new File(“hello.txt”);
File file2=new File(“hi.txt”);
FileInputStream fis=newFileInputStream(file1);
FileOutputStream fos=newFileOutputStream(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];intlen;while ((len=isr.read(cbuf))!=-1)
{
osw.write(cbuf,0,len);
}
isr.close();
osw.close();
}
}
还没有评论,来说两句吧...