java.ByteArrayInputStream-ByteArrayOutputStream

ByteArrayInputStream和ByteArrayOutputStream

内存虚拟文件或者内存映像文件就是把内存中的一块数据存储缓冲区,虚拟成一个文件,原来该写入硬盘文件上的内容可以被写入到这个内存中,原来该从硬盘文件中读取的内容也可以在内存中读取。
而要在内存中定义一个大的内存缓冲区,这个内存缓冲区通常就是一个字节数组,在java中专门定义了这两个类用于以IO流的方式来完成对字节数组的读写来支持类似虚拟文件或者内存映像文件的类似功能

ByteArrayInputStream的两个构造函数
ByteArrayInputStream(byte [] buf) 使用一个字节数组当中的所有数据作为数据源,以后程序可以向输入流一样读取这个字节数组当中的数据
ByteArrayInputStream(byte[] buf,int offset,int length)

ByteArrayOutputStream的两个构造函数
ByteArrayOutputStream()创建一个32字节的缓冲区
ByteArrayOutputStream(int) 根据参数大小设置缓冲区
这两个构造函数创建的缓冲区在数据过多的时候都会自动增长
创建缓冲区以后,我们的程序就可以把它像虚拟文件一样写入数据,当写完数据,就可以调用ByteArrayOutputStream的一个方法把这其中的内容当做一个字节数组来返回

用这两个类可以提高运行效率,不用访问硬盘直接在内存中读写。

  1. import java.io.*;  
  2. class ByteArrayTest {  
  3.       
  4.     public static void main(String[] args) {  
  5.         // TODO: Add your code here  
  6.         String tmp="abcdefjklmnopqrst";  
  7.         byte [] src=tmp.getBytes();  
  8.         ByteArrayInputStream input=new ByteArrayInputStream(src);  
  9.         ByteArrayOutputStream output=new ByteArrayOutputStream();//这里不用传递字节数组,ByteArrayOutputStream会自动创建一个32字节的缓冲区用来写入数据"Creates a new byte array output stream."  
  10.         transform(input,output);  
  11.         byte[] result=output.toByteArray(); //public byte[] toByteArray() "Creates a newly allocated byte array. Its size is the current size of this output stream and the valid contents of the buffer have been copied into it."  
  12.   
  13.         System.out.println(new String(result));  
  14.         System.out.println(new String(src));  
  15.     }  
  16.       
  17.     public static void transform(InputStream in,OutputStream out){  
  18.         int ch=0;  
  19.         try{  
  20.             while((ch=in.read())!=-1){  
  21.             int upperCh=/*(int)*/Character.toUpperCase((char)ch); //char表示的范围比int小  
  22.             out.write(upperCh);  
  23.             }  
  24.         }catch(Exception e){  
  25.             e.printStackTrace();  
  26.         }  
  27.     }     
  28. }  

 

StringReader和StringWriter类来以字符IO流的方式处理字符串


转:http://blog.csdn.net/rcoder/article/details/6108744


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值