Example usage for java.nio.channels FileChannel transferTo

List of usage examples for java.nio.channels FileChannel transferTo

Introduction

In this page you can find the example usage for java.nio.channels FileChannel transferTo.

Prototype

public abstract long transferTo(long position, long count, WritableByteChannel target) throws IOException;

Source Link

Document

Transfers bytes from this channel's file to the given writable byte channel.

Usage

From source file:com.igormaznitsa.jcp.utils.PreprocessorUtils.java

public static void copyFile(@Nonnull final File source, @Nonnull final File dest,
        final boolean copyFileAttributes) throws IOException {
    assertNotNull("Source is null", source);
    assertNotNull("Destination file is null", dest);

    if (source.isDirectory()) {
        throw new IllegalArgumentException("Source file is directory");
    }// w  w w  . ja v  a  2s . c o m

    if (!dest.getParentFile().exists() && !dest.getParentFile().mkdirs()) {
        throw new IOException("Can't make directory [" + getFilePath(dest.getParentFile()) + ']');
    }

    FileChannel fileSrc = null;
    FileChannel fileDst = null;
    final FileInputStream fileSrcInput = new FileInputStream(source);
    FileOutputStream fileOutput = null;
    try {
        fileSrc = fileSrcInput.getChannel();
        fileOutput = new FileOutputStream(dest);
        fileDst = fileOutput.getChannel();
        long size = fileSrc.size();
        long pos = 0L;
        while (size > 0) {
            final long written = fileSrc.transferTo(pos, size, fileDst);
            pos += written;
            size -= written;
        }
    } finally {
        IOUtils.closeQuietly(fileSrcInput);
        IOUtils.closeQuietly(fileOutput);
        IOUtils.closeQuietly(fileDst);
        IOUtils.closeQuietly(fileSrc);
    }

    if (copyFileAttributes) {
        copyFileAttributes(source, dest);
    }
}

From source file:com.hipu.bdb.util.FileUtils.java

/**
  * Copy up to extent bytes of the source file to the destination
  */*from   w w w. ja  v  a  2 s.com*/
  * @param src
  * @param dest
  * @param extent Maximum number of bytes to copy
 * @param overwrite If target file already exits, and this parameter is
  * true, overwrite target file (We do this by first deleting the target
  * file before we begin the copy).
 * @return True if the extent was greater than actual bytes copied.
  * @throws FileNotFoundException
  * @throws IOException
  */
public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite)
        throws FileNotFoundException, IOException {
    boolean result = false;
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists());
    }
    if (dest.exists()) {
        if (overwrite) {
            dest.delete();
            LOGGER.finer(dest.getAbsolutePath() + " removed before copy.");
        } else {
            // Already in place and we're not to overwrite.  Return.
            return result;
        }
    }
    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel fcin = null;
    FileChannel fcout = null;
    try {
        // Get channels
        fis = new FileInputStream(src);
        fos = new FileOutputStream(dest);
        fcin = fis.getChannel();
        fcout = fos.getChannel();
        if (extent < 0) {
            extent = fcin.size();
        }

        // Do the file copy
        long trans = fcin.transferTo(0, extent, fcout);
        if (trans < extent) {
            result = false;
        }
        result = true;
    } catch (IOException e) {
        // Add more info to the exception. Preserve old stacktrace.
        // We get 'Invalid argument' on some file copies. See
        // http://intellij.net/forums/thread.jsp?forum=13&thread=63027&message=853123
        // for related issue.
        String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent "
                + extent + " got IOE: " + e.getMessage();
        if ((e instanceof ClosedByInterruptException)
                || ((e.getMessage() != null) && e.getMessage().equals("Invalid argument"))) {
            LOGGER.severe("Failed copy, trying workaround: " + message);
            workaroundCopyFile(src, dest);
        } else {
            IOException newE = new IOException(message);
            newE.initCause(e);
            throw newE;
        }
    } finally {
        // finish up
        if (fcin != null) {
            fcin.close();
        }
        if (fcout != null) {
            fcout.close();
        }
        if (fis != null) {
            fis.close();
        }
        if (fos != null) {
            fos.close();
        }
    }
    return result;
}

From source file:edu.stanford.epad.common.util.EPADFileUtils.java

public static File copyFile(File src, File dst) {
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    try {//from www .  ja v  a 2 s .  c o  m
        inChannel = new FileInputStream(src).getChannel();
        outChannel = new FileOutputStream(dst).getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
        return dst;
    } catch (Exception e) {
        log.warning("Error copying file, from " + src.getAbsolutePath() + " to " + dst.getAbsolutePath(), e);
    } finally {
        try {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        } catch (IOException e) {
        }
    }
    return null;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.FileUtil.java

public static boolean copyFile(final String sourceFilename, final String destFilename) {
    boolean success = false;
    FileChannel source = null;
    FileChannel destination = null;
    FileInputStream sourceStream = null;
    FileOutputStream destinationStream = null;
    final File destFile = new File(destFilename);
    final File sourceFile = new File(sourceFilename);
    try {/* w w w  . ja  va 2 s. c  o  m*/
        final long size = sourceFile.length();
        sourceStream = new FileInputStream(sourceFile);
        destinationStream = new FileOutputStream(destFile);
        source = sourceStream.getChannel();
        destination = destinationStream.getChannel();
        long toTransfer = size;
        while (toTransfer > 0) {
            toTransfer -= source.transferTo(size - toTransfer, toTransfer, destination);
        }
        success = true;
    } catch (IOException iox) {
        try {
            logger.error(
                    "Unable to copy " + sourceFile.getCanonicalPath() + " to " + destFile.getCanonicalPath(),
                    iox);
        } catch (IOException iox2) {
            logger.error("Unable to copy " + sourceFile.getName() + " OR get the canonical name", iox2);
        }
    } finally {
        try {
            if (source != null) {
                source.close();
                source = null;
            }
            if (destination != null) {
                destination.close();
                destination = null;
            }
            if (sourceStream != null) {
                sourceStream.close();
                sourceStream = null;
            }
            if (destinationStream != null) {
                destinationStream.close();
                destinationStream = null;
            }
        } catch (IOException iox3) {
            logger.error("Unable to close stream?!?", iox3);
        }
    }
    return success;
}

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

private static long copyFileChannel(final FileChannel src, final WritableByteChannel dest, final int bufferSize)
        throws IOException {
    long bytes = 0L;
    long time = -System.currentTimeMillis();
    long size = src.size();
    while (bytes < size) {
        long bytesToTransfer = Math.min(bufferSize, size - bytes);
        long bytesTransfered = src.transferTo(bytes, bytesToTransfer, dest);

        bytes += bytesTransfered;/*w w  w. ja v a  2s. co m*/

        if (LOGGER.isDebugEnabled()) {
            long percentage = Math.round(bytes / ((double) size) * 100.0);
            LOGGER.debug("overall bytes transfered: " + bytes + " progress " + percentage + "%");
        }

    }

    if (LOGGER.isDebugEnabled()) {
        time += System.currentTimeMillis();
        double kBps = (bytes / 1024.0) / (time / 1000.0);
        LOGGER.debug("Transfered: " + bytes + " bytes in: " + (time / 1000.0) + " s -> " + kBps + " kbytes/s");
    }
    return bytes;
}

From source file:com.almunt.jgcaap.systemupdater.DownloadService.java

public void copy(File src, File dst) throws IOException {
    FileInputStream inStream = new FileInputStream(src);
    FileOutputStream outStream = new FileOutputStream(dst);
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    inStream.close();//from w  w w  .  jav a2 s.c om
    outStream.close();
}

From source file:com.geekandroid.sdk.sample.crop.ResultActivity.java

private void copyFileToDownloads(Uri croppedFileUri) throws Exception {
    String downloadsDirectoryPath = Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
    String filename = String.format("%d_%s", Calendar.getInstance().getTimeInMillis(),
            croppedFileUri.getLastPathSegment());

    File saveFile = new File(downloadsDirectoryPath, filename);

    FileInputStream inStream = new FileInputStream(new File(croppedFileUri.getPath()));
    FileOutputStream outStream = new FileOutputStream(saveFile);
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    inStream.close();/*from   w  w w .  j  av  a  2  s  .com*/
    outStream.close();

    showNotification(saveFile);
}

From source file:org.openmrs.module.formentry.FormEntryUtil.java

/**
 * Generates an expanded 'starter XSN'. This starter is essentially a blank XSN template to play
 * with in Infopath. Should be used similar to
 * <code>org.openmrs.module.formentry.FormEntryUtil.expandXsnContents(java.lang.String)</code>
 * Generates an expanded 'starter XSN'. This starter is essentially a blank XSN template to play
 * with in Infopath. Should be used similar to
 * <code>org.openmrs.formentry.FormEntryUtil.expandXsnContents(java.lang.String)</code>
 * //from  w  w  w  .  ja va2s. co m
 * @return File directory holding blank xsn contents
 * @throws IOException
 */
public static File getExpandedStarterXSN() throws IOException {

    // temp directory to hold the new xsn contents
    File tempDir = FormEntryUtil.createTempDirectory("XSN-starter");
    if (tempDir == null)
        throw new IOException("Failed to create temporary directory");

    // iterate over and copy each file in the given folder
    File starterDir = getResourceFile(FormEntryConstants.FORMENTRY_STARTER_XSN_FOLDER_PATH);
    for (File f : starterDir.listFiles()) {
        File newFile = new File(tempDir, f.getName());
        FileChannel in = null, out = null;
        try {
            in = new FileInputStream(f).getChannel();
            out = new FileOutputStream(newFile).getChannel();
            in.transferTo(0, in.size(), out);
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }

    return tempDir;
}

From source file:net.librec.util.FileUtil.java

/**
 * fast file copy/* w w  w .j a va 2  s  .co  m*/
 *
 * @param source source file
 * @param target target file
 * @throws Exception if error occurs
 */
public static void copyFile(File source, File target) throws Exception {

    FileInputStream fis = new FileInputStream(source);
    FileOutputStream fos = new FileOutputStream(target);
    FileChannel inChannel = fis.getChannel();
    FileChannel outChannel = fos.getChannel();

    // inChannel.transferTo(0, inChannel.size(), outChannel);
    // original -- apparently has trouble copying large files on Windows

    // magic number for Windows, 64Mb - 32Kb
    int maxCount = (64 * 1024 * 1024) - (32 * 1024);
    long size = inChannel.size();
    long position = 0;
    while (position < size) {
        position += inChannel.transferTo(position, maxCount, outChannel);
    }

    inChannel.close();
    outChannel.close();
    fis.close();
    fos.close();
}

From source file:ar.com.init.agros.license.LicenseVerifier.java

public void installLicense(String file) throws Exception {

    File licenseFile = new File(file);
    if (!isMasterLicense(file)) {
        licenseManager = new LicenseManager(createLicenseParam());
        licenseManager.install(licenseFile);
    } else {/*w  w w.ja v  a  2s .c om*/
        logger.fine("Using master license");
    }
    File installedFile = new File(INSTALLED_LICENSE_FILE);

    if (!installedFile.exists()) {
        FileChannel in = (new FileInputStream(licenseFile)).getChannel();
        FileChannel out = (new FileOutputStream(installedFile)).getChannel();
        in.transferTo(0, licenseFile.length(), out);
        in.close();
        out.close();
    }
}