有没有办法从java File对象中获取netty ByteBuf?我正在尝试使用Custom Snappy类来验证校验和。下面是我的代码,我想在File
变量中获取bytebuf
对象。
import io.netty.buffer.ByteBuf;
File file = new File("boot.zip");
ByteBuf byteBuf = Unpooled.buffer(128);
byteBuf.writeBytes(new FileInputStream(file));
int expectedChecksum = Snappy.calculateChecksum(byteBuf);
logger.info("checksum = "+expectedChecksum);
boolean checksumValid = true;
try {
CustomSnappy.validateChecksum(expectedChecksum, byteBuf);
} catch(DecompressionException e) {
checksumValid = false;
e.printStackTrace();
logger.error("DecompressionException in checksum calculation " + e);
} catch(Exception e) {
checksumValid = false;
e.printStackTrace();
logger.error("Exception in checksum calculation " + e);
}
我使用了Unpooled.buffer(128),但它给了我No signature of method :io.netty.buffer.UnpooledHeapByteBuf.writeBytes() is applicable for argument types: (java.io.FileInputStream) values: [java.io.FileInputStream@28b6520b]
答案 0 :(得分:5)
您可以从FileChannel创建MappedByteBuf并通过Unpooled.wrappedBuffer(..)将其包装在ByteBuffer中。
答案 1 :(得分:1)
如果您使用的是JDK 1.7,java.nio.file.Files
的类可以通过大量静态方法轻松实现。
ByteBuf buffer = Unpooled.copiedBuffer(Files.readAllBytes(new File(this.getClass().getResource("/requests/overPackageRequest").getFile()).toPath()));
答案 2 :(得分:1)
以下是如何“从MappedByteBuf
创建FileChannel
并通过ByteBuffer
将其包装在Unpooled.wrappedBuffer(..)
中的示例”
try {
File file = new File(filename);
FileInputStream fileInputStream = new FileInputStream(file);
FileChannel fileChannel = fileInputStream.getChannel();
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
ByteBuf byteBuf = Unpooled.wrappedBuffer(mappedByteBuffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
答案 3 :(得分:0)
您可以使用方法ByteBuf#writeBytes(InputStream)
。这应该有用,但我没有测试它。
ByteBuf buffer = // see http://stackoverflow.com/a/15088238/834
buffer.writeBytes(new FileInputStream(file), file.length());
请参阅http://netty.io/4.0/api/io/netty/buffer/ByteBuf.html#writeBytes(java.io.InputStream,%20int)
该文档显示了如何创建新的ByteBuf
:http://netty.io/4.0/api/io/netty/buffer/Unpooled.html