简体   繁体   中英

Using ordinary stream writers/readers with piped streams

Consider the following test code.

I am trying to find out if I can use piped streams like "normal" I/O streams, together with the commonly used Reader and Writer implementations (specifically, another part of the code base I am working on demands that I use OutputStreamWriter).

The problem here is that nothing appears to show up on the read end. The program at least appears to correctly write the message to the write-end of the pipe, but when trying to read from the other end I block indefinetly, or if I (as in this case) check for available bytes, the call returns 0.

What am I doing wrong?

public class PipeTest {

private InputStream input;
private OutputStream output;

public PipeTest() throws IOException {

    input = new PipedInputStream();
    output = new PipedOutputStream((PipedInputStream)input);

}

public void start() {

    Stuff1 stuff1 = new Stuff1(input);
    Stuff2 stuff2 = new Stuff2(output);

    Thread thread = new Thread(stuff1);
    thread.start();
    Thread thread2 = new Thread(stuff2);
    thread2.start();
}

public static void main(String[] args) throws IOException {

    new PipeTest().start();
}

private static class Stuff1 implements Runnable {

    InputStream inputStream;

    public Stuff1(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public void run() {

        String message;
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        try {
            //message = reader.readLine();
            System.out.println("Got message!");
            System.out.println(inputStream.available());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

private static class Stuff2 implements Runnable {

    OutputStream outputStream;

    public Stuff2(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    @Override
    public void run() {

        String message = "Hej!!\n";

        OutputStreamWriter writer = new OutputStreamWriter(outputStream);
        try {
            writer.write(message);
            System.out.println("Wrote message!");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}

As you are never reading from the read end, it is impossible to see how you could possibly arrive at that conclusion, and any such conclusion is therefore baseless and invalid.

All you are doing is printing available() at an arbitrary point in time, which isn't sufficient to prove that nothing ever shows up at the read end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM