首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ReadableByteChannel和TransferFrom()编写InputStream

使用ReadableByteChannel和TransferFrom()编写InputStream
EN

Stack Overflow用户
提问于 2020-06-05 09:39:35
回答 1查看 135关注 0票数 0

代码在Grails Web应用程序的几个函数中被拆分,但这里有这样的想法

代码语言:javascript
复制
MultipartFile mf = request.getPart();    
InputStream is = mf.getInputSteam();
Long size = mf.getSize();

ReadableByteChannel source = Channels.newChannel(inputStream);
FileChannel target = new FileOutputStream(new File('/path/to/file.jpg')).getChannel();
target.transferFrom(source, 0, size);

大小正确,InputStream有效,ReadableByteChannel / FileOutputStream已正确创建,但没有任何内容写入输出文件。

我宁愿用经典的'transfer‘方法编码,但我尝试了buffer方法,效果并不好

代码语言:javascript
复制
ByteBuffer buff = ByteBuffer.allocate(bufferSize)
FileChannel target = new FileOutputStream(targetFile).getChannel()
ReadableByteChannel source = Channels.newChannel(inputStream)

while (source.read(buff) >= 0 || buff.position() > 0) {
                buff.flip()
                target.write(buff)
                buff.compact()
            }

我遗漏了什么?

EN

回答 1

Stack Overflow用户

发布于 2020-06-07 00:51:27

检查返回大小传输的transferFrom()的结果使用try()确保这些流在您期望的时候关闭-特别是对于"new FileOutputStream“/ "FileChannel target”

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62206765

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档