Java IO流中的处理流之二 :转换流

Java IO流中的处理流之二 :转换流转换流提供了在字节流和字符流之间的转换 字节流中的数据都是字符时 转成字符流操作更高效

大家好,欢迎来到IT知识分享网。

前文回顾



前言

前面我们介绍了Java IO流原理及流的体系、FileReader、FileWriter、FileInputStream、FileOutputStream 的使用。今天我们接着来介绍关于IO流中处理流的其他内容。希望能够对学习的伙伴提供些许的帮助。


一、转换流是什么?

1、InputStreamReader

2、OutputStreamWriter

3、执行流程

在这里插入图片描述

二、代码实现

1.InputStreamReader的使用

代码如下(示例):

package zzz.xxx.java; import org.junit.Test; import java.io.*; public class InputStreamTest { 
       /* InputStreamReader的使用,实现字节的输入流转换为字符的输入流 */ @Test public void test1() { 
       InputStreamReader isr = null; try { 
       FileInputStream fis = new FileInputStream("dbcp.txt"); // InputStreamReader isr = new InputStreamReader(fis); // 使用系统默认的字符集 // 参数2 指明了字符集,具体使用什么字符集,取决于文件dbcp.txt保存时使用的字符集 isr = new InputStreamReader(fis, "UTF-8"); char[] cbuf = new char[20]; int len; while ((len = isr.read(cbuf)) != -1) { 
       String str = new String(cbuf, 0, len); System.out.print(str); } } catch (IOException e) { 
       e.printStackTrace(); } finally { 
       if (isr != null) { 
       try { 
       isr.close(); } catch (IOException e) { 
       e.printStackTrace(); } } } } } 

2.综合使用 InputStreamReader 和 OutputStreamWriter

代码如下(示例):

package zzz.xxx.java; import org.junit.Test; import java.io.*; public class InputStreamTest { 
       /* 综合使用 InputStreamReader 和 OutputStreamWriter 实现以UTF-8输入,以GBK输出 */ @Test public void test2() { 
       InputStreamReader isr = null; OutputStreamWriter osw = null; try { 
       // 造文件、造流 File file1 = new File("dbcp.txt"); File file2 = new File("dbcp_gbk.txt"); FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2); isr = new InputStreamReader(fis, "utf-8"); osw = new OutputStreamWriter(fos, "gbk"); // 读写过程 char[] cbuf = new char[20]; int len; while ((len = isr.read(cbuf)) != -1) { 
       osw.write(cbuf, 0, len); } } catch (IOException e) { 
       e.printStackTrace(); } finally { 
       // 关闭资源 if (osw != null) { 
       try { 
       osw.close(); } catch (IOException e) { 
       e.printStackTrace(); } } if (isr != null) { 
       try { 
       isr.close(); } catch (IOException e) { 
       e.printStackTrace(); } } } } } 

总结

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/133079.html

(0)
上一篇 2025-07-26 18:00
下一篇 2025-07-26 18:10

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信