文件操作流:
现在想要实现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();
}
}
结果一样但是流程不同。
掌握即可,已经有更方便的方法使用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)