【JAVA IO】_内存操作流笔记

来源:互联网 发布:手机淘宝秒杀怎么刷新 编辑:程序博客网 时间:2024/05/16 04:18

【JAVA IO】_内存操作流笔记

分类: Java
【JAVA IO】_内存操作流笔记

本章目标
掌握内存操作流的使用

ByteArrayInputStream和ByteArrayOutputStream
之前所讲解的程序中,输出和输入都是从文件中来的,当然,也可以将输出的位置设置在内存之上。此时就要使用ByteArrayInputStream、ByteArrayOutputStream来完成输入、输出功能了。

ByteArrayInputStream的主要完成将内容写入到内存之中,而
ByteArrayOutputStream主要是将内存中的数据输出。

格式:
public class ByteArrayInputStream extends InputStream

public class ByteArrayOutputStream extends OutputStream

构造方法:
public ByteArrayInputStream(byte[] buf)

下面利用内存操作流完成一个大小写字母转化的程序

[java] view plaincopyprint?
  1. import java.io.*;  
  2. public class ByteArrayDemo01{  
  3.     public static void main(String[] args){  
  4.         String str = "HELLOWORLD";  
  5.         ByteArrayInputStream bis = null;  
  6.         ByteArrayOutputStream bos = null;  
  7.   
  8.         bis = new ByteArrayInputStream(str.getBytes());  
  9.         bos = new ByteArrayOutputStream();  
  10.         int temp = 0;  
  11.         while((temp=bis.read())!=-1){  
  12.             char c = (char)temp;  
  13.             bos.write(Character.toLowerCase(c));//将字符变小写  
  14.         }  
  15.         //所有的数据就全部都在ByteArrayOutputStream中  
  16.         String newStr = bos.toString();    //取出内容  
  17.         try{  
  18.             bis.close();  
  19.         }catch(IOException e){  
  20.             e.printStackTrace();  
  21.         }  
  22.         System.out.println(newStr);  
  23.     }  
  24. }  


如果要想把一个字符变为小写,可以通过包装类:Character

实际上此时还可以通过向上转型的关系为OutputStream或InputStream实例化

[java] view plaincopyprint?
  1. import java.io.*;  
  2. public class ByteArrayDemo02{  
  3.     public static void main(String[] args)throws Exception{  
  4.         String str = "HELLOWORLD";  
  5.         InputStream bis = null;  
  6.         OutputStream bos = null;  
  7.   
  8.         bis = new ByteArrayInputStream(str.getBytes());  
  9.         bos = new ByteArrayOutputStream();  
  10.         int temp = 0;  
  11.         while((temp=bis.read())!=-1){  
  12.             char c = (char)temp;  
  13.             bos.write(Character.toLowerCase(c));//将字符变小写  
  14.         }  
  15.         //所有的数据就全部都在ByteArrayOutputStream中  
  16.         String newStr = bos.toString();    //取出内容  
  17.         try{  
  18.             bis.close();  
  19.         }catch(IOException e){  
  20.             e.printStackTrace();  
  21.         }  
  22.         System.out.println(newStr);  
  23.     }  
  24. }  

实际上,以上的操作可以很好的体现对象的多态性,通过实例化其子类的不同,完成的功能也不同,也就相当于输出也就不同,如果是文件,则使用FileXxx,如果是内存,则使用ByteArrayXxx.
0 0
原创粉丝点击