0%

java中IO(三):内存流简单讲解

介绍

在io(二)当中介绍的都是关于文件进行简单的IO处理,除了文件了IO处理之外,其实还有一种内存的IO操作,对于内存的操作流我们称为内存操作类。内存操作流主要有:ByteArrayInputStream、ByteArrayOutputStream、CharArrayReader、CharArrayWriter这四个类

讲解

一、ByteArrayInputStream

类的定义:

1
2
public class ByteArrayInputStream
extends InputStream

构造函数:

1
2
3
4
5
ByteArrayInputStream(byte[] buf)
//Creates a ByteArrayInputStream so that it uses buf as its buffer array.

ByteArrayInputStream(byte[] buf, int offset, int length)
//Creates ByteArrayInputStream that uses buf as its buffer array

可以看得出来ByteArrayInputStream继承自InputStream,并且他接收一个字节数组byte[]进行初始化。文档上描述是ByteArrayInputStream包含一个内部缓冲区,该缓冲区包含可以从流中读取的字节。内部计数器跟踪由read方法提供的下一个字节。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 public static void main(String[] args) {

try {
String str = "hellow world";
//实例化时,将你需要的数据保存到内存当中
InputStream inputStream = new ByteArrayInputStream(str.getBytes());
byte[] b = new byte[20];

int temp = inputStream.read(b);
System.out.println("读取的字节数:"+temp);
System.out.println("读取的内容:"+new String(b));
inputStream.close();
} catch (IOException e) {
//TODO: handle exception
System.out.println(e);
}
}

结果:

1
2
读取的字节数:12
读取的内容:hellow world

发现用法其实和前面讲的文件类io操作差不多,而且功能似乎也挺鸡肋。

二、ByteArrayOutputStream

类的定义:

1
2
public class ByteArrayOutputStream
extends OutputStream

构造函数:

1
2
3
4
5
ByteArrayOutputStream()
//Creates a new byte array output stream.

ByteArrayOutputStream(int size)
//Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

可以看得出来ByteArrayOutputStream是继承自OutputStream,用法和前面的讲解的FileOutputStream类似,个人觉得区别是FileOutputStream是将字节数组写到文件当中,而ByteArrayOutputStream将字节数组写到内存缓冲区当中,因为功能比较鸡肋,对应的代码也不展示了。文档上的描述为此类实现输出流,在该流中,数据被写入字节数组。缓冲区随着数据写入自动增长。可以使用toByteArray()和toString()检索数据。

三、CharArrayReader

类的定义:

1
2
public class CharArrayReader
extends Reader

构造函数:

1
2
3
4
CharArrayReader(char[] buf)
//Creates a CharArrayReader from the specified array of chars.
CharArrayReader(char[] buf, int offset, int length)
//Creates a CharArrayReader from the specified array of chars.

文档上描述为此类实现了可用作字符输入流的字符缓冲区。其实和上面的ByteArrayInputStream类型。

四、CharArrayWriter

类的定义:

1
2
public class CharArrayWriter
extends Writer

构造函数:

1
2
3
4
5
CharArrayWriter()
//Creates a new CharArrayWriter.

CharArrayWriter(int initialSize)
//Creates a new CharArrayWriter with the specified initial size.

文档上的描述:此类实现了可用作Writer的字符缓冲区。将数据写入流时,缓冲区会自动增长。可以使用toCharArray()和toString()检索数据。有些类似于上面的ByteArrayOutputStream

总结

这四个内存流的操作都比较简单,使用也不是很多,所以写的也比较水了解一下即可。在以前好像是使用文件流和内存流一起来读取文件,但是随着java不断地更新出现了许多更好地方法,所以内存流使用地也少了起来,个人觉得了解一下即可。