How to find the size of a ReadableByteChannel in Java?

牧云@^-^@ 提交于 2020-01-07 02:47:26

问题


I am converting a blob from a database into a PDF, using Java's Channel classes. When using a Channel's transferFrom( ) method, you are supposed to specify the maximum number of bytes to be transferred.

How are you supposed to find this maximum number of bytes when ReadableByteChannels don't have a size( ) method like other Channels?

Is a ReadableByteChannel not the right tool for the job since it doesn't have a size( ) method? I'm just using Long.MAX_VALUE which doesn't seem right.

Example code:

// Get the blob in an InputStream
InputStream inStream = rs.getBinaryStream("SomeBlob");

// Create a ReadableByteChannel from that InputStream
ReadableByteChannel rbc = Channels.newChannel(inStream);

// Make a FileOutputStream to write the PDF From
FileOutputStream outStream = new FileOutputStream("MyPDF.PDF");
outStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

// Close stuff
inStream.close();
outStream.close();
rbc.close();

回答1:


Use Long.MAX_VALUE, or the length of the Blob if you can get it.

'Length of a ReadableByteChannel' is meaningless in general. Consider a SocketChannel whose peer never closes the connection.



来源:https://stackoverflow.com/questions/35092213/how-to-find-the-size-of-a-readablebytechannel-in-java

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