Java基础知识强化之IO流笔记58:内存操作流

1. 内存操作流:

用来操作处理临时存储的信息的

(1)操作字节数组:

ByteArrayInputStream

ByteArrayOutputStream

代码示例:

 1 package cn.itcast_02;
 2 
 3 import java.io.ByteArrayInputStream;
 4 import java.io.ByteArrayOutputStream;
 5 import java.io.IOException;
 6 
 7 /*
 8  * 内存操作流:用于处理临时存储信息的,程序结束,数据就从内存中消失。
 9  * 字节数组:
10  *         ByteArrayInputStream
11  *         ByteArrayOutputStream
12  * 字符数组:
13  *         CharArrayReader
14  *         CharArrayWriter
15  * 字符串:
16  *         StringReader
17  *         StringWriter
18  */
19 public class ByteArrayStreamDemo {
20     public static void main(String[] args) throws IOException {
21         // 写数据
22         // ByteArrayOutputStream()
23         ByteArrayOutputStream baos = new ByteArrayOutputStream();
24 
25         // 写数据
26         for (int x = 0; x < 10; x++) {
27             baos.write(("hello" + x).getBytes());
28         }
29 
30         // 释放资源
31         // 通过查看源码我们知道这里什么都没做,所以根本需要close()
32         // baos.close();
33 
34         // public byte[] toByteArray()
35         byte[] bys = baos.toByteArray();
36 
37         // 读数据
38         // ByteArrayInputStream(byte[] buf)
39         ByteArrayInputStream bais = new ByteArrayInputStream(bys);
40 
41         int by = 0;
42         while ((by = bais.read()) != -1) {
43             System.out.print((char) by);
44         }
45 
46         // bais.close();
47     }
48 }

运行效果,如下:

(2)操作字符数组

CharArrayReader

CharArrayWriter

(3)操作字符串

StringReader

StringWriter

原文地址:https://www.cnblogs.com/hebao0514/p/4871911.html