随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
posts - 398,comments - 0,views - 13万

文件操作流:

 

 现在想要实现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   时间完全不够用啊  阅读(355)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示