Here you can find the source of copyToTempFile(final InputStream is, final String prefix, final String suffix)
Parameter | Description |
---|---|
is | the input stream |
prefix | the prefix part of the file name |
suffix | the suffix part of the file name |
Parameter | Description |
---|
public static File copyToTempFile(final InputStream is, final String prefix, final String suffix) 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 { /**/* w w w . ja v a 2 s . c o m*/ * Copies the stream to the temporary file. * * @param is the input stream * @param prefix the prefix part of the file name * @param suffix the suffix part of the file name * @return the temporary file * @throws java.io.IOException I/O Exception */ public static File copyToTempFile(final InputStream is, final String prefix, final String suffix) throws IOException { return copyToFile(is, File.createTempFile(prefix, suffix)); } /** * 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; } }