内存操作流

内存操作流

内存操作流一般作用于处理临时信息, 因为临时信息不需要保存,使用后就可以删除。

  • 操作字节数组
    • ByteArrayInputStream(byte[] buf)
    • ByteArrayOutputStream()
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class MemoryStream {

	public static void main(String[] args) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		//写入数据到内存中
		baos.write("Hello World".getBytes());
		
		//得到内存中的数据
		byte[] data = baos.toByteArray();
		System.out.println(new String(data));
		
		//内存输入流有点鸡肋,也是得到内存数据
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		int ch;
		while ((ch = bais.read()) != -1) {
			System.out.print((char)ch);
		}
	}

}

编译结果:

Hello World
Hello World

  • 操作字符数组
    • CharArrayReader
    • CharArrayWrite
import java.io.*;

public class MemoryStream2 {
	public static void main(String[] args) throws IOException{
		//输出字符串到内存
		CharArrayWriter caw = new CharArrayWriter();
		char[] chs = {'m', 'a', 'n', '!'};
		caw.write(chs);
		//从内存中获得字符串
		System.out.println(caw.toString());
		System.out.println(caw.toCharArray());
		
		caw.close();
		//鸡肋输入流
		char[] data = caw.toCharArray();
		CharArrayReader car = new CharArrayReader(data);
		int ch;
		while((ch = car.read()) != -1) {
			System.out.print((char)ch);
		}
	}
}

编译结果:

man!
man!
man!

  • 操作字符串
    • StringReader
    • StringWriter·
import java.io.*;

public class MemoryStream3 {
	public static void main(String[] args) throws IOException{
		StringWriter sw = new StringWriter();
		sw.write("hello world");
		System.out.println(sw.toString());
		sw.close();
		
		//鸡肋的输入流
		String str = sw.toString();
				
		StringReader sr = new StringReader(str);
		
		int ch;
		while((ch = sr.read()) != -1) {
			System.out.print((char)ch);
		}
	}
}

编译结果:

hello world
hello world

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值