Java File Copy nio copyToFile(final InputStream is, final File file)

Here you can find the source of copyToFile(final InputStream is, final File file)

Description

Copies the stream to the temporary file.

License

Apache License

Parameter

Parameter Description
is the input stream
file the file

Exception

Parameter Description
IOException I/O Exception

Return

the temporary file

Declaration

public static File copyToFile(final InputStream is, final File file) throws IOException 

Method Source Code


//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;
    }
}

Related

  1. copyFile(FileChannel srcFc, File dstFile)
  2. copyFile(final File source, final File dest)
  3. copyFile(final File source, final File target)
  4. copyFile(final File source, final File target)
  5. copyFileByMapped(String sourcePath, String targetPath)
  6. copyToTempFile(final InputStream is, final String prefix, final String suffix)
  7. copyToTmpFile(InputStream in, String prefix, String suffix)
  8. fileCopy(File source, File destination)
  9. fileCopy(File source, File target)