Java threadchain

Is it wrong to maintain links to further downstream threads in the filter chain and reuse those lower level threads or even to exchange one type of stream for another? For instance:

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 threads, for example. if i want to write some lines of text into a stream followed by binary data or vice versa?

+4
source share
4 answers

This may be done in some cases, but it is error prone. You must be careful about buffers, etc., such as the headers of the ObjectOutputStream stream.

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

To do this, all you need to know is that you can convert text to binary data and vice versa, but you always need to specify an encoding. However, it is also error prone because people tend to use API methods that use the default encoding for the platform, and of course, you mostly implement a parser for a custom binary file format - a lot can go wrong.

In general, if you are creating a file format, especially when mixing text and binary data, it is better to use the existing infrastructure, for example , Google protocol buffers

+3
source

If you need to do this, you need to do this. Therefore, if you are dealing with an external addiction that you do not have, you just need to do it.

I think bad style is the fact that you will need to do this. If you sometimes had to send binary data, and the text to others, it would be better to have some kind of message object and send the object itself through wiring using Serialization. The overhead of data is not too large if it is properly structured.

+3
source

I don’t understand why not. I mean, implementations of various stream classes should protect you from writing invalid data. As long as you read it the same way, and your code is otherwise clear, I don’t understand why this would be a problem.

Style does not always mean that you should do it the way you saw how others do it. As long as this is logical, and someone reading the code will see that (and why) you are doing this without requiring a bunch of comments, then I don’t understand what the problem is.

+1
source

Since you are missing each other, this is probably good. But it may be cleaner to use one OutputStream and just use os.write(string.getBytes()); to write lines.

0
source

Source: https://habr.com/ru/post/1379384/


All Articles