当前位置: 首页 > news >正文

java基础-IO(4)管道流 PipedOutputStream、PipedInputStream、PipedReader、PipedWriter

管道

提到管道,第一印象就是水管或者地下管道,一节接着一节,形如下图。
在这里插入图片描述

管道流

"流"从上一个管道 ——-> 下一个管道。又细分为字节流和字符流。
在这里插入图片描述


字节流(PipedOutputStream、PipedInputStream)
在这里插入图片描述
如果从上一个管道到下一个管道,只是走个过场岂不是没有任何意义,既然要处理就需要逗留,逗留就意味着需要暂存,字节流使用字节数组存储,字符流使用字符数据存储。
在这里插入图片描述


PipedOutputStream 核心源码:

PipedOutputStream extends OutputStream//指向下一节"管道"
private PipedInputStream sink;//向外写数据(流出当前管道)
write(*****);//构造方法
public PipedOutputStream(PipedInputStream snk)  throws IOException {connect(snk);}//连接下一个"管道"
public synchronized void connect(PipedInputStream snk) throws IOException {if (snk == null) {throw new NullPointerException();//一个管道只能被一个管道连接} else if (sink != null || snk.connected) {  throw new IOException("Already connected");}sink = snk;snk.in = -1;snk.out = 0;//管道已被连接的标识snk.connected = true;
}

PipedInputStream 核心源码:


PipedInputStream extends InputStream//数据暂存的地方
protected byte buffer[];//数组默认大小
private static final int DEFAULT_PIPE_SIZE = 1024;//是否已经被连接的标识
boolean connected = false;//构造方法
public PipedInputStream() {initPipe(DEFAULT_PIPE_SIZE);
}private void initPipe(int pipeSize) {if (pipeSize <= 0) {throw new IllegalArgumentException("Pipe Size <= 0");}buffer = new byte[pipeSize];
}//自定义数组大小
public PipedInputStream(int pipeSize) {initPipe(pipeSize);
}//指定上一个"管道是谁"
public PipedInputStream(PipedOutputStream src) throws IOException {this(src, DEFAULT_PIPE_SIZE);
}//即指明上一个"管道是谁",又自定义数组大小
public PipedInputStream(PipedOutputStream src, int pipeSize)throws IOException {initPipe(pipeSize);connect(src);
}

在这里插入图片描述


案例:一个字符串从上一个管道写到下一个管道。
在这里插入图片描述

 public static void main(String[] args) throws IOException {PipedOutputStream po = new PipedOutputStream();PipedInputStream pi = new PipedInputStream();Thread t1 = new Thread(() -> {try {int b;while ((b = pi.read()) != -1) {System.out.print((char) b);}pi.close();} catch (IOException e) {throw new RuntimeException(e);}});//链接管道po.connect(pi);String str1 = "hello world";byte[] bytes = str1.getBytes();Thread t2 = new Thread(() -> {try {po.write(bytes);po.flush();po.close();} catch (IOException e) {throw new RuntimeException(e);}});t2.start();t1.start();}

PipedReader、PipedWriter 字符管道类似于字节管道,只不过使用字符数组存储数据。


http://www.mrgr.cn/news/22450.html

相关文章:

  • 逆元
  • C语言函数
  • Js实现继承的6种方式
  • 一文彻底搞懂:Java基本数据类型详解
  • C++11 atomic和内存序
  • 谈谈ES搜索引擎
  • 2409wtl,网浏包装
  • 前端页面加载由模糊到清晰的实现方案
  • 生信代码入门:从零开始掌握生物信息学编程技能
  • 使用 BentoML快速实现Llama-3推理服务
  • SpringMVC基础
  • 人工智能领域的微调指的是什么?
  • 如何选择开源云服务
  • PostgreSQL技术内幕9:PostgreSQL事务原理解析
  • 小琳AI课堂:深入学习Transformer模型
  • c++进阶——unordered的封装
  • 【Jupyter Notebook】更改代码默认保存路径
  • 【EI会议征稿通知】第十一届机械工程、材料和自动化技术国际会议(MMEAT 2025)
  • Android 12 SystemUI下拉状态栏禁止QuickQSPanel展开
  • context canceled 到底谁在作祟?