Java IO--内存操作流ByteArrayInputStream/ByteArrayOutputStream

ByteArrayInputStream和ByteArrayOutputStream



此时操作的时候,应该以内存为操作点。




利用其完成一个大小写转换的程序:
import java.io.* ;
public class ByteArrayDemo01{
	public static void main(String args[]){
		String str = "HELLOWORLD" ;		// 定义一个字符串,全部由大写字母组成
		ByteArrayInputStream bis = null ;	// 内存输入流
		ByteArrayOutputStream bos = null ;	// 内存输出流
		bis = new ByteArrayInputStream(str.getBytes()) ;	// 向内存中输出内容
		bos = new ByteArrayOutputStream() ;	// 准备从内存ByteArrayInputStream中读取内容
		int temp = 0 ;
		while((temp=bis.read())!=-1){
			char c = (char) temp ;	// 读取的数字变为字符
			bos.write(Character.toLowerCase(c)) ;	// 将字符变为小写
		}
		// 所有的数据就全部都在ByteArrayOutputStream中
		String newStr = bos.toString() ;	// 取出内容
		try{
			bis.close() ;
			bos.close() ;
		}catch(IOException e){
			e.printStackTrace() ;
		}
		System.out.println(newStr) ;
	}
};

总结:

1、内存操作流的操作对象一定是以内存为准,不要以程序为准。
2、实际上此时可以通过向上转型的关系为OutputStream或InputStream实例化。
import java.io.* ;
public class ByteArrayDemo01{
	public static void main(String args[]) throws Exception{
		String str = "HELLOWORLD" ;		// 定义一个字符串,全部由大写字母组成
		InputStream bis = null ;	// 内存输入流
		OutputStream bos = null ;	// 内存输出流
		bis = new ByteArrayInputStream(str.getBytes()) ;	// 向内存中输出内容
		bos = new ByteArrayOutputStream() ;	// 准备从内存ByteArrayInputStream中读取内容
		int temp = 0 ;
		while((temp=bis.read())!=-1){
			char c = (char) temp ;	// 读取的数字变为字符
			bos.write(Character.toLowerCase(c)) ;	// 将字符变为小写
		}
		// 所有的数据就全部都在ByteArrayOutputStream中
		String newStr = bos.toString() ;	// 取出内容
		try{
			bis.close() ;
			bos.close() ;
		}catch(IOException e){
			e.printStackTrace() ;
		}
		System.out.println(newStr) ;
	}
};

实际上,以上的操作可以很好的体现对象的多态性,通过实例化其子类的不同,完成的功能也不同,也就相当于输出位置也就不同。如果是文件,则使用FileXxx,如果是内存,则使用ByteArrayXxx。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值