字节数组流和数据流
字节数组流
基于内存操作,内部维护着一个字节数组,我们可以利用流的读取机制来处理字符串,无需关闭
ByteArrayInputStream
包含一个内部缓冲区,该缓冲区包含从流中读取的字节,内部计数器跟踪read方法要提供的下一个字节,关闭ByteArrayInputStream无效,此类中的方法在关闭流后仍可以使用,而不会产生任何IOException
ByteArrayOutputStream
此类实现了一个输出流,其中的数据被写入一个byte数组,缓冲区会随着数据的不断写入而自动增长,可使用toByteArray()和toString()获取数据,关闭ByteArrayOutputStream无效,此类中的方法在关闭此流后仍可以被调用,而不会产生任何IoException。
小案例:输出字符串中的字母
public class Test10 {
public static void main(String[] args) {
String str = " fdkfjsk**^%$%>";
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int len = -1;//每次读取的字节
while ((len = inputStream.read()) != -1) {
if (len >= 65 && len <= 90 || len >= 98 && len <= 122) {
outputStream.write(len);
}
}
// 此时无需关闭,原因:字节数组流是基于内存的操作流
System.out.println(outputStream.toString());
}
}
数据流:
DataInputStream
:数据输入流允许应用程序以与机器无关的方式从底层输入流中读取基本java数据类型,应用程序可以使用数据输出流写入稍后由数据输入流读取的数据,DataInputStream对于多线程访问不一定是安全的,线程安全是可选的,它由此类方法使用者负责
DataOutputStream
:数据输出流允许应用程序以适当方式将基本java数据类型写入输出流中,然后,应用程序可以使用数据输入流将数据读入
代码演示:
public class Test11 {
public static void main(String[] args) {
write();
reader();
}
private static void reader() {
InputStream in = null;
try {
in = new FileInputStream("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\lili.txt");
BufferedInputStream bis = new BufferedInputStream(in);
DataInputStream dis = new DataInputStream(bis);
//按顺序
char c = dis.readChar();
int read = dis.read();
String s = dis.readUTF();
double v = dis.readDouble();
System.out.println(c + "," + read + "," + s + "," + v);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void write() {
try {
OutputStream outputStream = new FileOutputStream("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\lili.txt");
BufferedOutputStream out = new BufferedOutputStream(outputStream);
DataOutputStream dos = new DataOutputStream(out);
dos.writeChar('1');
dos.write(2);
dos.writeUTF("丽丽");
dos.writeDouble(12.23);
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!