java(5)--IO流之PipedInputStream和PipedOutputStream
2015-11-30 16:23
453 查看
PipedInputStream和PipedOutputStream顾名思义,管道流,管道流和多线程相结合,因为管道输入流需要和管道输出流相连接,连接之后如果输入流先执行,输出流后执行,一开始的时候管道里并没有字节流存在,因此read会无法执行,导致程序无法运行,因此管道流必须和多线程相结合。
附上代码:
接下来的时间会将框架知识还有多线程知识还有异常知识陆续写入进来。
附上代码:
``` import java.io.*; public class PipedStream { public static void main(String[] args) throws IOException { // TODO 自动生成的方法存根 PipedInputStream pis=new PipedInputStream(); PipedOutputStream pos=new PipedOutputStream(); pis.connect(pos);//连接管道 new Thread(new Input(pis)).start(); //创建输入流线程 new Thread(new Output(pos)).start();//创建输出流线程 } } class Input implements Runnable{ private PipedInputStream in; public Input(PipedInputStream in) { // TODO 自动生成的构造函数存根 this.in=in; } public void run(){ try { byte[] buf=new byte[1024]; System.out.println("读取开始"); int len=in.read(); System.out.println(new String(buf,0,len)); in.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 throw new RuntimeException("读取管道失败"); } } } class Output implements Runnable{ private PipedOutputStream out; Output(PipedOutputStream out){ this.out=out; } public void run(){ try { System.out.println("写入开始"); Thread.sleep(1000); //为了避免线程死等,可以将这个线程挂起,切换线程执行 out.write("hello piper".getBytes()); out.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 throw new RuntimeException("管道写入失败"); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 throw new RuntimeException("线程出问题了"); } } }
接下来的时间会将框架知识还有多线程知识还有异常知识陆续写入进来。
相关文章推荐
- 在 Java 中应用设计模式 - Factory Method
- java枚举类型示例
- Spring事务管理的三种方式
- 为什么C#动态调用Java的cxf多了bool型参数
- java设计模式----外观模式(门面模式)
- intllij idea 出现 java.lang.AssertionError:upexpected content storage modification错误信息
- java、js 对于四舍五入、向上取整、向下取整
- Myeclipse自动生成的get set方法 加上文本注释
- Bean的生命周期
- 常见java异常
- 一、编写高质量的代码—Java开发中通用的方法和准则(笔记)
- SpringMVC下打包文件的下载
- 基于JDK API实现文件的压缩与解压
- 使用Spring发送基于freemarker模板的邮件
- SpringMVC下Excel文件的上传下载实现
- MyBatis与Spring集成
- Java编码规范—约定也要配置
- Java集合框架应用
- Selection sort
- Spring 注解 之 @Transactional