Getting Progress of ObjectOutputStream/ObjectInputStream
I recently figured out how to use ObjectOutputStream and ObjectInputStream to send objects over a simple Java socket connection between a server and a client. I was wondering if I wanted to transfer an object that might be large in size, for example an image, is it possible to put a thread that keeps track of the progress of how much data has been sent/开发者_StackOverflow中文版received? If the answer to this question isn't very direct, could someone explain how I might go about doing something similar? Thanks in advance!
The Apache Commons IO library has a pair of classes CountingInputStream
and CountingOutputStream
that implement byte counting input/output stream filters.
If you insert these into your stream chains you can track the number of bytes read or written. (These filters have to be inserted somewhere between the physical input/output stream and object stream.)
You could implement the same thing yourself by subclassing the FilterInputStream
and FilterOutputStream
classes. And there is even a Swing class called ProgressMonitorInputStream
that might implement exactly what you need.
I would suggest writing instrumented InputStream and OutputStream which just pipe to/from streams provided at construction time while counting the number of bytes going through.
Then you can build your stream chain with one of the above inserted -- just be careful not to have too many buffers between your instrumented OutputStream and the network, or you'd be counting bytes going into the buffers rather than into the network.
You can also use count the total bytes to be sent, by writing yet another output stream which just throws the data away and writing your objects once to it through your instrumented output stream.
精彩评论