一:内存流
1、内存流主要用来操作内存:
ByteArrayInputStream和ByteArrayOutputStream
2、输入和输入可以把文件作为数据源,也可以把内存作为数据源。
ByteArrayInputStream主要完成将内容从内存读入程序之中
ByteArrayOutputStream的功能主要是将数据写入到内存中。
注意:因为这两个流没有使用系统资源,所有不用关闭,也不需要抛出异常.
例题:读取内存中的内容
package memory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class ByteArrayInputStreamDemo {
public static void main(String[] args) {
String data="你好,内存流";
ByteArrayInputStream bis=new ByteArrayInputStream(data.getBytes()); // 构造方法中传入的字节数组就是要读取的字节数组
byte[] b=new byte[1024]; // 自定义缓冲区
try {
int len=bis.read(b);
System.out.println("读取的内容是:"+new String(b,0,len));
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
例题:向内存中写入内容
package memory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class BoSToString {
public static void main(String[] args) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
bos.write("hello world中国".getBytes());
System.out.println("已经写入到内存中的字符串是:" + bos.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
ByteArrayOutputStream获取数据的方式:
1. public byte[] toByteArray()
创建一个新分配的字节数组。它的大小是这个输出流的当前大小和缓冲区的有效内容的副本
2. public String toString()
使用该平台的默认字符集将缓冲区的内容转换为字符串
package memory;
import java.io.*;
public class ByteArrayOutputStreamDemo {
public static void main(String[] args) {
File srcFile=new File("c:"+File.separator+"IO流练习"+File.separator+"IO练习一.txt");
File destFile=new File("c:"+File.separator+srcFile.getName());
InputStream input=null;
OutputStream out=null;
ByteArrayOutputStream bos=new ByteArrayOutputStream(); // 写入内存中的内存输出流
try {
input=new FileInputStream(srcFile); // 读取源文件的输入流
out=new FileOutputStream(destFile); // 写入目标文件的输出流
byte[] b=new byte[1024];
int len=0;
while((len=input.read(b))!=-1){
bos.write(b, 0, len); // 不断写入内存中
}
byte[] data=bos.toByteArray(); // 创建一个新分配的字节数组。它的大小是这个输出流的当前大小和缓冲区的有效内容的副本
out.write(data); // 将图片数据一次性写入目标文件中
System.out.println("写入成功!");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
out.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果: