Here you can find the source of copyToFile(final InputStream is, final File file)
Parameter | Description |
---|---|
is | the input stream |
file | the file |
Parameter | Description |
---|---|
IOException | I/O Exception |
public static File copyToFile(final InputStream is, final File file) throws IOException
//package com.java2s; //License from project: Apache License import java.io.*; import java.nio.channels.ReadableByteChannel; import java.nio.channels.FileChannel; import java.nio.channels.Channels; import java.nio.ByteBuffer; public class Main { /**//from www . ja v a2s .c o m * Copies the stream to the temporary file. * * @param is the input stream * @param file the file * @return the temporary file * @throws IOException I/O Exception */ public static File copyToFile(final InputStream is, final File file) throws IOException { final FileOutputStream fos = new FileOutputStream(file); ReadableByteChannel source = null; FileChannel target = null; try { source = Channels.newChannel(is); target = fos.getChannel(); final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); while (source.read(buffer) != -1) { // prepare the buffer to be drained buffer.flip(); // make sure the buffer was fully drained. while (buffer.hasRemaining()) { target.write(buffer); } // make the buffer empty, ready for filling buffer.clear(); } } finally { if (source != null) { source.close(); } if (target != null) { target.close(); } } return file; } }