内存流的使用

内存操作流

内存操作流:用于处理临时存储信息的,程序结束,数据就从内存中消失。
名称规则: 以字节结尾的必须使用字节输出流结尾(in/out putStream)否则使用字符。

字节数组:

  • ByteArrayInputStream
  • ByteArrayOutputStream
  • ==用法==
public class ByteArrayStreamDemo {
    public static void main(String[] args) throws IOException {
        // 写数据
        // ByteArrayOutputStream()
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // 写数据
        for (int x = 0; x < 10; x++) {
            baos.write(("hello" + x).getBytes());
        }

        // 释放资源
        // 通过查看源码我们知道这里什么都没做,所以根本需要close()
        // baos.close();

        // public byte[] toByteArray()
        byte[] bys = baos.toByteArray();

        // 读数据
        // ByteArrayInputStream(byte[] buf)
        ByteArrayInputStream bais = new ByteArrayInputStream(bys);

        int by = 0;
        while ((by = bais.read()) != -1) {
            System.out.print((char) by);
        }

        // bais.close();
    }
}

字符数组

  • CharArrayReader
  • CharArrayWriter
public static void main(String[] args) throws IOException {
        CharArrayWriter cw=new CharArrayWriter();
        cw.write("hello".toCharArray());
        char[] a=cw.toCharArray();
        System.out.println(a);
        CharArrayReader cr=new CharArrayReader(a);
        char[] buf=new char[1024];
        int len;
        while((len=cr.read(buf))!=-1){
            System.out.print(new String(buf,0,len));

        }
    }

字符串

  • StringReader
  • StringWriter
 public static void main(String[] args) throws IOException {
       String first="hello";
       StringWriter sw=new StringWriter();
       sw.write("hello");
       StringReader sr=new StringReader("hehe");
       char[] buf=new char[1024];
        int len;
        while((len=sr.read(buf))!=-1){
            System.out.print(new String(buf,0,len));

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值