如何在 Java 中找到 ReadableByteChannel 的大小?

How to find the size of a ReadableByteChannel in Java?

我正在使用 Java 的频道 类 将 blob 从数据库转换为 PDF。使用 Channel 的 transferFrom( ) 方法时,您应该指定要传输的最大字节数。

当 ReadableByteChannels 没有像其他 Channels 那样的 size( ) 方法时,您应该如何找到这个最大字节数?

ReadableByteChannel 没有 size( ) 方法,是不是适合这项工作的工具?我只是在使用 Long.MAX_VALUE,这似乎不对。

示例代码:

// 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();

使用Long.MAX_VALUE,或者Blob的长度,如果你能得到的话。

'Length of a ReadableByteChannel'一般是没有意义的。考虑一个 SocketChannel,其对等方从不关闭连接。