6、IO--内存操作流

 

 

输入和输出可以基于文件实现

也可以将输出的位置设置再内存

 

此时需要使用ByteArrayInputStreamByteArrayOutputStream来完成输入和输出功能

ByteArrayInputStream 是将内容写到内存中

ByteArrayOutputStream 是将内存中的数据输出

 

ByteArrayInputStream 主要方法:

public ByteArrayInputStream(byte [] buf)  将全部的内容写到内存中

public ByteArrayInputStream(byte [] buf,int offset,int length)  将指定范围的内容全部写道内存中

  

ByteArrayOutputStream  主要方法:

public ByteArray OutputStream()   创建对象

public void write( int b)   将内容从内存中输出

 

public static void main(String[] args) {
        
        String str="HelloWord";
        
        //内存输入流---内容写到内存中
        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(c);
        }
        //所有的数据全部都在ByteArrayOutputStream
        String newStr = bos.toString();
        
        try {
            bis.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        System.out.println(newStr);
        
    }

 

内存流一般再生成一些临时信息时才会使用

这些临时信息如果保存再文件中

代码执行结束后还需要删除这个临时文件

此时,将这些信息存放在内存中最合适的

 

posted @ 2019-05-05 19:24  MrChengs  阅读(203)  评论(0编辑  收藏  举报