ByteArrayInputStream和ByteArrayOutputStream使用-黑马程序员

本文演示了如何使用ByteArrayInputStream和ByteArrayOutputStream进行字节流的读写操作,并通过自定义方法实现字符到大写字符的转换。

ByteArrayInputStream 包含一个内部缓冲区,该缓冲区存储从流中读取的字节。内部计数器跟踪 read 方法要提供的下一个字节。

关闭 ByteArrayInputStream 无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何 IOException


ByteArrayOutputStream 此类实现了一个输出流,其中的数据被写入一个字节数组。缓冲区会随着数据的不断写入而自动增长。可使用 toByteArray()toString() 检索数据。

关闭 ByteArrayOutputStream 无效。在关闭此流后且没有生成 IOException 时,可以调用此类中的该方法


@Test
	public void test2() {
		
		
		byte[] buf = "abcdefghijklmnopqrstuvwxyz".getBytes();
		//像输入流中输入一段信息
		ByteArrayInputStream in = new ByteArrayInputStream(buf);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		transform(in, out);
		
		//转换成数组,然后组装成字符串打印
		System.out.println(new String(out.toByteArray()));
		
	}
	
		
	private void transform(InputStream in,OutputStream out){
		
		try {
			int ch= 0;
			while((ch=in.read())!=-1){
				int upper = Character.toUpperCase((char)ch);
				out.write(upper);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		
	}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值