今天看到毕老师第21的视频,模仿视频写了一个使用管道流的程序
但是抛出了两个异常,自己解决了一个,该有一个我找不到解决的办法,大神帮我看看怎么解决。。
3Q- package day21;
- import java.io.IOException;
- import java.io.PipedInputStream;
- import java.io.PipedOutputStream;
- class ReaderPip implements Runnable {
- private PipedInputStream pis;
- ReaderPip(PipedInputStream pis) {
- this.pis = pis;
- }
- public void run() {
- try {
- byte[] bt = new byte[1024];
- int len = 0;
- while ((len = pis.read(bt)) != -1) {
- String str = new String(bt, 0, len);
- System.out.println(str);
- }
- } catch (IOException e) {
- e.printStackTrace();
- // throw new RuntimeException("reader fail");
- } finally {
- try {
- pis.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- class WritePip implements Runnable {
- private PipedOutputStream pos;
- WritePip(PipedOutputStream pos) {
- this.pos = pos;
- }
- public void run() {
- try {
- pos.write("嘿咻嘿咻。。。".getBytes());
-
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- pos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- public class PipedStreamDemo {
- public static void main(String args[]) {
- PipedInputStream pis = new PipedInputStream();
- PipedOutputStream pos = new PipedOutputStream();
- try {
- pis.connect(pos);
- new Thread(new ReaderPip(pis)).start();
- new Thread(new WritePip(pos)).start();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- pis.close();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- pos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码 异常提醒如下:
java.io.IOException: Pipe closed
at java.io.PipedInputStream.checkStateForReceive(PipedInputStream.java:244)
at java.io.PipedInputStream.receive(PipedInputStream.java:210)
at java.io.PipedOutputStream.write(PipedOutputStream.java:132)
at java.io.OutputStream.write(OutputStream.java:58)
at day21.WritePip.run(PipedStreamDemo.java:46)
at java.lang.Thread.run(Thread.java:619) |