Java – how to write InputStream to a file using NiO?
I write InputStream to a file in the following ways:
private void writeToFile(InputStream stream) throws IOException { String filePath = "C:\\Test.jpg"; FileChannel outChannel = new FileOutputStream(filePath).getChannel(); ReadableByteChannel inChannel = Channels.newChannel(stream); ByteBuffer buffer = ByteBuffer.allocate(1024); while(true) { if(inChannel.read(buffer) == -1) { break; } buffer.flip(); outChannel.write(buffer); buffer.clear(); } inChannel.close(); outChannel.close(); }
I wonder if this is the right way to use NiO I read a method, filechannel Transferfrom, which has three parameters:
>Readablebytechannel SRC > long warehouse > Long Count
In my case, I only have SRC, and I have no location and quantity. Is there any way to use this method to create files?
Also, for image, is there a better way to create images only from InputStream and NiO?
Any information is very useful to me There are similar problems in so, but I can't find any specific solution suitable for my situation
Solution
No, that's not true You are at risk of losing data The NiO replication cycle of the specification is as follows:
while (in.read(buffer) >= 0 || buffer.position() > 0) { buffer.flip(); out.write(buffer); buffer.compact(); }
Note the changed loop conditions, which are responsible for refreshing the output on EOS and using compact () instead of clear (), so as to ensure the possibility of writing
Similarly, the canonical transferto() / transferfrom() loop is as follows:
long offset = 0; long quantum = 1024*1024; // or however much you want to transfer at a time long count; while ((count = out.transferFrom(in,offset,quantum)) > 0) { offset += count; }
It must be called circularly because it cannot guarantee the transfer of the entire quantum