现在的位置: 首页 > 综合 > 正文

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

2013年09月20日 ⁄ 综合 ⁄ 共 1565字 ⁄ 字号 评论关闭

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

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

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

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

格式:
public class ByteArrayInputStream extends InputStream

public class ByteArrayOutputStream extends OutputStream

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

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

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();
        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();
        }catch(IOException e){
            e.printStackTrace();
        }
        System.out.println(newStr);
    }
}

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

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

import java.io.*;
public class ByteArrayDemo02{
    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();
        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();
        }catch(IOException e){
            e.printStackTrace();
        }
        System.out.println(newStr);
    }
}

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

【上篇】
【下篇】

抱歉!评论已关闭.