Java File Copy nio copyToTmpFile(InputStream in, String prefix, String suffix)

Here you can find the source of copyToTmpFile(InputStream in, String prefix, String suffix)

Description

copy To Tmp File

License

Open Source License

Declaration

public static File copyToTmpFile(InputStream in, String prefix, String suffix) throws IOException 

Method Source Code


//package com.java2s;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
    public static File copyToTmpFile(InputStream in, String prefix, String suffix) throws IOException {
        File tempFile = File.createTempFile(prefix, suffix);
        tempFile.deleteOnExit();/*  w  ww .ja v  a 2 s .c o  m*/
        copy(in, new FileOutputStream(tempFile));
        return tempFile;
    }

    public static void copy(InputStream in, OutputStream out) throws IOException {
        final ReadableByteChannel inputChannel = Channels.newChannel(in);
        final WritableByteChannel outputChannel = Channels.newChannel(out);
        // copy the channels
        copy(inputChannel, outputChannel);
        // closing the channels
        inputChannel.close();
        outputChannel.close();
    }

    private static void copy(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
        while (src.read(buffer) != -1) {
            // prepare the buffer to be drained
            buffer.flip();
            // write to the channel, may block
            dest.write(buffer);
            // If partial transfer, shift remainder down
            // If buffer is empty, same as doing clear()
            buffer.compact();
        }
        // EOF will leave buffer in fill state
        buffer.flip();
        // make sure the buffer is fully drained.
        while (buffer.hasRemaining()) {
            dest.write(buffer);
        }
    }
}

Related

  1. copyFile(final File source, final File target)
  2. copyFile(final File source, final File target)
  3. copyFileByMapped(String sourcePath, String targetPath)
  4. copyToFile(final InputStream is, final File file)
  5. copyToTempFile(final InputStream is, final String prefix, final String suffix)
  6. fileCopy(File source, File destination)
  7. fileCopy(File source, File target)
  8. fileCopy(File sourceFile, File destFile)
  9. fileCopy(File src, File dest)