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

11 篇文章 0 订阅

 1.字节数组流

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

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

 

示例代码:

Java代码   收藏代码
  1. public static void main(String[] args) {  
  2.   
  3.         // 创建一个字节数组输出流对象  
  4.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  5.   
  6.         String data = "好好学习,天天向上";  
  7.   
  8.         try {  
  9.             //写入字符串  
  10.             out.write(data.getBytes());  
  11.             out.close();  
  12.         } catch (IOException e) {  
  13.             e.printStackTrace();  
  14.         }  
  15.           
  16.         //------------------------  
  17.         //根据字节数组构建字节数组输入流---out关闭后还可以调用toByteArray()方法  
  18.         ByteArrayInputStream in=new ByteArrayInputStream(out.toByteArray());  
  19.         byte[]bytes=new byte[512];  
  20.         int len=-1;  
  21.         StringBuilder sb=new StringBuilder();  
  22.         try {  
  23.             while((len=in.read(bytes))!=-1)  
  24.             {  
  25.                 sb.append(new String(bytes,0,len));  
  26.             }  
  27.             in.close();  
  28.         } catch (IOException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.   
  32.           
  33.         System.out.println("data: "+sb);  
  34.     }  

 运行结果:



 

2.字符串流

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

代码示例:

Java代码   收藏代码
  1. public static void main(String[] args) {  
  2.   
  3.         //写入操作  
  4.         StringWriter sw=new StringWriter();  
  5.           
  6.         try {  
  7.             sw.write("好好学习,天天向上");  
  8.             sw.close();  
  9.         } catch (IOException e1) {  
  10.             e1.printStackTrace();  
  11.         }  
  12.         //读取操作,根据一个字符串构造一个字符串输入流  
  13.         StringReader sr=new StringReader(sw.toString());  
  14.           
  15.         char[]chars=new char[10];  
  16.         int len=-1;  
  17.         StringBuilder sb=new StringBuilder();  
  18.         try {  
  19.             while((len=sr.read(chars))!=-1)  
  20.             {  
  21.                 sb.append(new String(chars,0,len));  
  22.             }  
  23.             sr.close();  
  24.         } catch (IOException e) {  
  25.             e.printStackTrace();  
  26.         }  
  27.           
  28.         System.out.println("data: "+sb);  
  29.     }  

 

运行结果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值