您的位置:首页 > 编程语言 > Java开发

Java基础巩固系列 InputStreamReader与OutputStreamWriter (转换流)

2019-04-04 20:39 399 查看

示意图:

 

代码示例:

[code]public class TestOtherStream {

/**
* 如何实现字节流与字符流之间的转换:
* 转换流:InputStreamReader  OutputStreamWriter
* 编码:字符串    ---->  字节数组
* 解码:字节数组  ---->  字符串
*/
@Test
public void test1() {
BufferedReader br = null;
BufferedWriter bw = null;
try {
//解码
File file = new File("hello.txt");
FileInputStream fis = new FileInputStream(file); //字节输入流
InputStreamReader isr = new InputStreamReader(fis, "GBK"); //把字节输入流存到输入流读取器
br = new BufferedReader(isr);   //缓冲字符输入流 读取 输入流读取器
//编码
File file1 = new File("hello2.txt");
FileOutputStream fos = new FileOutputStream(file1); //字节输出流
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");    //字节输出流存到输出流编写器
bw = new BufferedWriter(osw);   //缓冲字符输出流 读取 输出流编写器
String str;
while ((str = br.readLine()) != null) {
bw.write(str);
bw.newLine();
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐