IO流之字节数组流和字符串流

 1.字节数组流

      字 节数组输出流ByteArrayOutputStream实现了一个输出流,其中的数据被写入一个byte数组,缓冲区会随着数据的不断写入而自动增长。 关闭ByteArrayOutputStream流无效,此类中的方法在关闭该流后还可以使用,而不会产生任何IOException,数据存放在内存。

      字节数组输出流ByteArrayInputStream实现了一个输入流,ByteArrayInputStream包含一个缓冲区,该缓冲区包含从流 中读取的字节,内部计数器跟踪read方法要读取的下一个字节。关闭ByteArrayInputStream流后,此类的方法也可以继续使用。因为数据 是在内存中。

 

示例代码:

public static void main(String[] args) {

		// 创建一个字节数组输出流对象
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		String data = "好好学习,天天向上";

		try {
			//写入字符串
			out.write(data.getBytes());
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//------------------------
		//根据字节数组构建字节数组输入流---out关闭后还可以调用toByteArray()方法
		ByteArrayInputStream in=new ByteArrayInputStream(out.toByteArray());
		byte[]bytes=new byte[512];
		int len=-1;
		StringBuilder sb=new StringBuilder();
		try {
			while((len=in.read(bytes))!=-1)
			{
				sb.append(new String(bytes,0,len));
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		
		System.out.println("data: "+sb);
	}

 运行结果:



 

2.字符串流

    字符串流的数据存放在内存中,关闭流后方法还可以继续调用,而不会产生任何IOException。StringWriter是字符串输入流,可以用其回收再字符串缓冲区的输出来构造字符串。

代码示例:

public static void main(String[] args) {

		//写入操作
		StringWriter sw=new StringWriter();
		
		try {
			sw.write("好好学习,天天向上");
			sw.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		//读取操作,根据一个字符串构造一个字符串输入流
		StringReader sr=new StringReader(sw.toString());
		
		char[]chars=new char[10];
		int len=-1;
		StringBuilder sb=new StringBuilder();
		try {
			while((len=sr.read(chars))!=-1)
			{
				sb.append(new String(chars,0,len));
			}
			sr.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		System.out.println("data: "+sb);
	}

 

运行结果:



 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值