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

【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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

e421083458

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值