内存流的使用

来源:互联网 发布:餐饮软件开发 编辑:程序博客网 时间:2024/06/05 13:30

内存操作流

内存操作流:用于处理临时存储信息的,程序结束,数据就从内存中消失。
名称规则: 以字节结尾的必须使用字节输出流结尾(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));        }   }
原创粉丝点击