Java Question: How to connect an input stream to another's output

statik213

Golden Member
Oct 31, 2004
1,654
0
0
I have an inputstream that I'd like to get data from a Writer;

basically i'm reading and writing to serialports from Java and i don't have the hardware on me so i'm trying to simulate the data that would be available on these ports.

So I need to connect a Writer to an InputStream, I can then fool my program to think that the InputStream is from the serial port and then simulate what's arriving from teh seral port by writing to my Writer.

I've been trying to figure out the PipedInput/OutputStream classes and tried this sort off a thing:
PipedInputStream pin = new PipedInputStream();
PipedOutputStream pout = new PipedOutputStream(pin);

writer = new BufferedWriter(new OutputStreamWriter(pout, "US-ASCII"));

the effect I was *hoping* for was for something like:

writer.write("foo");
while(pin.available() > 0)
System.out.print((char) pin.read());

to print out "foo". but off course, this is not working, what am I doing wrong?
How cna I achieve this effect?

I know that pipes are meant for cross-thread stuff, but still :)



 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
No, you do have the right idea. And pipes don't really have to do with threads, you just have to be careful not to do a blocking read if you're writing from the same thread.

I don't know exactly what's going wrong, I'm looking into it :)
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
I just tried out your simplified example with and without the flush. It worked with the flush and didn't work without.

I'm not about to start debugging your real code :p Have you put in debug statements to be absolutely sure that stuff is actually getting put into your writer (since all writes are in either loops or ifs)? Maybe try replacing your pout with System.out, as shown in the example in the javadoc for OutputStreamWriter.