文件系列往期文章:
本文介绍如何将内存数组流的数据写入文件流中。即将内存数组流中的数据通过文件流写到磁盘上,也叫flush,或持久化。毕竟内存是短暂的,磁盘才是永恒。
流就像管道,数据就像管道里的水。管道最大的魅力就是可以连接,使水从一个管道流到另一个管道,流也一样。
之前我们分别介绍了文件流和内存数组流,既然他们是流,那就应该可以连接起来。那么如何从内存数组流写入文件流呢?
在 java 字节流入门(文件流)中,我们介绍了 FileOutputStream(FOS) 和 RandomAccessFile(RAF) 两种写文件的方式。那么,当我们在内存中使用 ByteArrayOutputStream(BAOS) 维护数据时,如何利用 FOS 和 RAF 写文件呢,本文介绍四种方法。
准备工作:
private static final Path path = Paths.get("src", "main", "resources", "test.myfile");
private static final File file = path.toFile();
private static int size = 1024*1024*800;
private static byte[] b1 = new byte[size];
private static ByteArrayOutputStream out = new ByteArrayOutputStream();
并将 b1 写入 out 中
out.write(b1);
writeTo写入FOS
首先,BAOS 有一个方法叫 writeTo(),这个方法可以将 BAOS 中的数据直接写入另一个字节输出流中。更准确的说法是,使用另一个字节输出流的 write() 方法将 BAOS 中的数据写出去。这里 BAOS 就和一个字节数组是等价的。
/**
* Writes the complete contents of this byte array output stream to
* the specified output stream argument, as if by calling the output
* stream's write method using <code>out.write(buf, 0, count)</code>.
&nb