Writing an InputStream with ReadableByteChannel and TransferFrom()

697 Views Asked by At

The code is split accross several functions of a Grails Web Application but here's the idea

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

The size is right, InputStream is valid and ReadableByteChannel / FileOutputStream are properly created, but nothing gets written to the output file.

I'd rather have it coded with the classic 'transfer' method but I tried the buffer method which works no better

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()
            }

What am I missing?

1

There are 1 best solutions below

0
DuncG On

Check the result of transferFrom() which returns size transferrde use try() to ensure these streams are closed when you expect - especially for "new FileOutputStream" / "FileChannel target"