Java IO流中的处理流之二 :转换流
前文回顾
Java IO流原理及流的体系——节点流(文件流)
Java IO流中的处理流之一:缓冲流
文章目录
- 前文回顾
- 前言
- 一、转换流是什么?
-
- 1、InputStreamReader
- 2、OutputStreamWriter
- 3、执行流程
- 二、代码实现
-
- 1.InputStreamReader的使用
- 2.综合使用 InputStreamReader 和 OutputStreamWriter
- 总结
前言
前面我们介绍了Java IO流原理及流的体系、FileReader、FileWriter、FileInputStream、FileOutputStream 的使用。今天我们接着来介绍关于IO流中处理流的其他内容。希望能够对学习的伙伴提供些许的帮助。
一、转换流是什么?
转换流提供了在字节流和字符流之间的转换,字节流中的数据都是字符时,转成字符流操作更高效。很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。
Java API提供了两个转换流:
InputStreamReader:将InputStream转换为Reader
OutputStreamWriter:将Writer转换为OutputStream
1、InputStreamReader
实现将字节的输入流按指定字符集转换为字符的输入流。
需要和InputStream“套接”。
2、OutputStreamWriter
实现将字符的输出流按指定字符集转换为字节的输出流。
需要和OutputStream“套接”。
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(); } } } }}
总结
以上就是今天分享的内容,介绍了IO流中的处理流之二:转换流的使用,需要详细教程的伙伴可私信联系。
来都来了,点赞 收藏 加关注再走吧 ~ ~ ~