Getting Progress of ObjectOutputStream/ObjectInputStream

别说谁变了你拦得住时间么 提交于 2019-12-25 15:53:34

问题


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/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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5366002/getting-progress-of-objectoutputstream-objectinputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!