Java--内存流

本文介绍了Java中的内存流,包括ByteArrayInputStream和ByteArrayOutputStream的用途。内存流允许从内存读取和写入数据,不涉及系统资源,因此无需关闭。文章通过示例展示了如何读取内存内容和向内存写入内容,并解释了ByteArrayOutputStream获取数据的两种方法:toByteArray()和toString()。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:内存流

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();
			}
		}
	}
}

运行结果:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值