随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。

文件操作流:

 

 现在想要实现IO操作,但是不想产生文件(临时文件)。可以以内存为终端进行操作。

内存操作流:

在Java里面提供有两类的内存操作流:

字节内存操作流:ByteArrayOutputStream、ByteArrayInputStream·

字符内存操作流:CharArrayWriter、CharArrayReader;

 

 

 

ByteArrayInputStream和ByteArrayOutputStream构造方法分析:

ByteArrayInputStream构造: public ByteArrayInputStream(byte[] buf)
ByteArrayOutputStream构造: public ByteArrayOutputStream();

实现案例:

import java.io.*;
import java.nio.charset.StandardCharsets;

public class MAIN {
    public static void main(String[] args) throws Exception {
        String str = "www.baidu.com";
        InputStream input =new ByteArrayInputStream(str.getBytes());    // 将数据保存在内存流中
        OutputStream output = new ByteArrayOutputStream();  // 读取内存中的数据
        int data = 0;
        while ((data = input.read()) != -1){    // 每次读取一个字节
            output.write(Character.toUpperCase(data));   // 保存大写后的数据
        }
        System.out.println(new String(res));
        input.close();
        output.close();
    }
}

下面是ByteArrayOutputStream中最重要的方法,可以获取内存中全部的数据:

获取数据:public byte[]toByteArray();
使用字符串的形式来获取:public String toString();
import java.io.*;
import java.nio.charset.StandardCharsets;

public class MAIN {
    public static void main(String[] args) throws Exception {
        String str = "www.baidu.com";
        InputStream input =new ByteArrayInputStream(str.getBytes());    // 将数据保存在内存流中
        // 必须使用子类本身来使用扩展方法(获取全部数据)
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int data = 0;
        while ((data = input.read()) != -1){    // 每次读取一个字节
            output.write(Character.toUpperCase(data));   // 保存大写后的数据
        }
        byte[] res = output.toByteArray();  // 获取全部数据
        System.out.println(new String(res));  // 自己处理数据
        input.close();
        output.close();
    }
}

 

 结果一样但是流程不同。

掌握即可,已经有更方便的方法使用。

 

posted on 2022-02-17 15:38  时间完全不够用啊  阅读(331)  评论(0编辑  收藏  举报