lxgr
lxgr

Reputation: 3797

Stream chaining in Java

Is it bad style to keep the references to streams "further down" a filter chain, and use those lower level streams again, or even to swap one type of stream for another? For example:

    OutputStream os = new FileOutputStream("file");
    PrintWriter pw = new PrintWriter(os);
    pw.print("print writer stream");
    pw.flush();
    pw = null;
    DataOutputStream dos = new DataOutputStream(os);
    dos.writeBytes("dos writer stream");
    dos.flush();
    dos = null;
    os.close();

If so, what are the alternatives if I need to use the functionality of both streams, e.g. if I want to write a few lines of text to a stream, followed by binary data, or vice versa?

Upvotes: 5

Views: 1909

Answers (4)

Kevin
Kevin

Reputation: 56049

Since you're flushing between, it's probably fine. But it might be cleaner to use one OutputStream and just use os.write(string.getBytes()); to write the strings.

Upvotes: 0

jefflunt
jefflunt

Reputation: 33954

I don't see why not. I mean, the implementations of the various stream classes should protect you from writing invalid data. So long as you're reading it back the same way, and your code is otherwise understandable, I don't see why that would be a problem.

Style doesn't always mean you have to do it the way you've seen others do it. So long as it's logical, and someone reading the code would see what (and why) you're doing it without you needing to write a bunch of comments, then I don't see what the issue is.

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346240

This can be done in some cases, but it's error-prone. You need to be careful about buffers and stuff like the stream headers of ObjectOutputStream.

if I want to write a few lines of text to a stream, followed by binary data, or vice versa?

For this, all you need to know is that you can convert text to binary data and back but always need to specify an encoding. However, it is also error-prone because people tend to use the API methods that use the platform default encoding, and of course you're basically implementing a parser for a custom binary file format - lots of things can go wrong there.

All in all, if you're creating a file format, especially when mixing text and binary data, it's best to use an existing framework like Google protocol buffers

Upvotes: 4

corsiKa
corsiKa

Reputation: 82559

If you have to do it, then you have to do it. So if you're dealing with an external dependency that you don't have control over, you just have to do it.

I think the bad style is the fact that you would need to do it. If you had to send binary data across sometimes, and text across at others, it would probably be best to have some kind of message object and send the object itself over the wire with Serialization. The data overhead isn't too much if structured properly.

Upvotes: 3

Related Questions