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:org.apache.solr.core.CoreContainer.java

/** Copies a src file to a dest file:
 *  used to circumvent the platform discrepancies regarding renaming files.
 *///from w  w w  .j a  va  2 s  . c o m
public static void fileCopy(File src, File dest) throws IOException {
    IOException xforward = null;
    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel fcin = null;
    FileChannel fcout = null;
    try {
        fis = new FileInputStream(src);
        fos = new FileOutputStream(dest);
        fcin = fis.getChannel();
        fcout = fos.getChannel();
        // do the file copy 32Mb at a time
        final int MB32 = 32 * 1024 * 1024;
        long size = fcin.size();
        long position = 0;
        while (position < size) {
            position += fcin.transferTo(position, MB32, fcout);
        }
    } catch (IOException xio) {
        xforward = xio;
    } finally {
        if (fis != null)
            try {
                fis.close();
                fis = null;
            } catch (IOException xio) {
            }
        if (fos != null)
            try {
                fos.close();
                fos = null;
            } catch (IOException xio) {
            }
        if (fcin != null && fcin.isOpen())
            try {
                fcin.close();
                fcin = null;
            } catch (IOException xio) {
            }
        if (fcout != null && fcout.isOpen())
            try {
                fcout.close();
                fcout = null;
            } catch (IOException xio) {
            }
    }
    if (xforward != null) {
        throw xforward;
    }
}

From source file:org.gcaldaemon.core.Configurator.java

public static final void copyFile(File from, File to) throws Exception {
    if (from == null || to == null || !from.exists()) {
        return;/*from  w w w  .  j  a  v a 2 s . co  m*/
    }
    RandomAccessFile fromFile = null;
    RandomAccessFile toFile = null;
    try {
        fromFile = new RandomAccessFile(from, "r");
        toFile = new RandomAccessFile(to, "rw");
        FileChannel fromChannel = fromFile.getChannel();
        FileChannel toChannel = toFile.getChannel();
        long length = fromFile.length();
        long start = 0;
        while (start < length) {
            start += fromChannel.transferTo(start, length - start, toChannel);
        }
        fromChannel.close();
        toChannel.close();
    } finally {
        if (fromFile != null) {
            fromFile.close();
        }
        if (toFile != null) {
            toFile.close();
        }
    }
}

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

public static void copy(final String sourceFilename, final String destFilename) throws IOException {

    FileInputStream sourceFileInputStream = null;
    FileChannel sourceChannel = null;
    FileOutputStream destFileOutputStream = null;
    FileChannel destChannel = null;

    try {//  www .  ja v  a2  s  .c  o  m
        File destFile = new File(destFilename);
        final File sourceFile = new File(sourceFilename);
        if (destFile.isDirectory()) {
            // use original file's name
            destFile = new File(destFile, sourceFile.getName());
        }

        //noinspection IOResourceOpenedButNotSafelyClosed
        sourceFileInputStream = new FileInputStream(sourceFile);
        //noinspection ChannelOpenedButNotSafelyClosed
        sourceChannel = (sourceFileInputStream).getChannel();

        //noinspection IOResourceOpenedButNotSafelyClosed
        destFileOutputStream = new FileOutputStream(destFile);
        //noinspection ChannelOpenedButNotSafelyClosed
        destChannel = (destFileOutputStream).getChannel();

        final long size = sourceFile.length();
        long toTransfer = size;
        while (toTransfer > 0) {
            toTransfer -= sourceChannel.transferTo(size - toTransfer, toTransfer, destChannel);
        }

    } finally {
        IOUtils.closeQuietly(sourceFileInputStream);
        IOUtils.closeQuietly(sourceChannel);
        IOUtils.closeQuietly(destFileOutputStream);
        IOUtils.closeQuietly(destChannel);
    }
}

From source file:org.paxle.crawler.fs.impl.FsCrawler.java

private File copyChanneled(final File file, final ICrawlerDocument cdoc, final boolean useFsync) {
    logger.info(String.format("Copying '%s' using the copy mechanism of the OS%s", file,
            (useFsync) ? " with fsync" : ""));

    final ITempFileManager tfm = this.contextLocal.getCurrentContext().getTempFileManager();
    if (tfm == null) {
        cdoc.setStatus(ICrawlerDocument.Status.UNKNOWN_FAILURE,
                "Cannot access ITempFileMananger from " + Thread.currentThread().getName());
        return null;
    }/*from www  . j  a  v  a 2 s .co  m*/

    FileInputStream fis = null;
    FileOutputStream fos = null;
    File out = null;
    try {
        out = tfm.createTempFile();
        fis = new FileInputStream(file);
        fos = new FileOutputStream(out);

        final FileChannel in_fc = fis.getChannel();
        final FileChannel out_fc = fos.getChannel();

        long txed = 0L;
        while (txed < in_fc.size())
            txed += in_fc.transferTo(txed, in_fc.size() - txed, out_fc);

        if (useFsync)
            out_fc.force(false);
        out_fc.close();

        try {
            detectFormats(cdoc, fis);
        } catch (IOException ee) {
            logger.warn(
                    String.format("Error detecting format of '%s': %s", cdoc.getLocation(), ee.getMessage()));
        }
    } catch (IOException e) {
        logger.error(String.format("Error copying '%s' to '%s': %s", cdoc.getLocation(), out, e.getMessage()),
                e);
        cdoc.setStatus(ICrawlerDocument.Status.UNKNOWN_FAILURE, e.getMessage());
    } finally {
        if (fis != null)
            try {
                fis.close();
            } catch (IOException e) {
                /* ignore */}
        if (fos != null)
            try {
                fos.close();
            } catch (IOException e) {
                /* ignore */}
    }
    return out;
}

From source file:com.kkbox.toolkit.image.KKImageRequest.java

private void moveFileTo(String originalPath, String targetPath) {
    fileLock.lock();/*ww  w  . ja  v  a  2 s .  c o m*/
    File targetFile = new File(targetPath);
    targetFile.delete();
    FileChannel originalChannel = null;
    FileChannel targetChannel = null;
    try {
        originalChannel = new FileInputStream(originalPath).getChannel();
        targetChannel = new FileOutputStream(targetPath).getChannel();
        originalChannel.transferTo(0, originalChannel.size(), targetChannel);
    } catch (IOException e) {
    }
    try {
        if (originalChannel != null)
            originalChannel.close();
        if (targetChannel != null)
            targetChannel.close();
    } catch (IOException e) {
    }
    fileLock.unlock();
}

From source file:org.apache.cordova.backgroundDownload.BackgroundDownload.java

private void copyFile(File src, File dest) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dest).getChannel();
    try {/*w w  w .ja  v a  2s .co  m*/
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null) {
            inChannel.close();
        }
        if (outChannel != null) {
            outChannel.close();
        }
    }
}

From source file:com.intervigil.micdroid.MainActivity.java

@Override
public void onExport(Recording r) {
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Log.w(TAG, "onExport: External media is not available");
        Toast.makeText(mContext, R.string.recording_options_export_external_media_unavailable,
                Toast.LENGTH_SHORT).show();
        return;//from   w ww  . ja  v a 2  s .  c om
    }
    File externalMusicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
    if (!externalMusicDir.exists() && !externalMusicDir.mkdirs()) {
        Log.e(TAG, "onExport: Failed to create external music directory");
        Toast.makeText(mContext, R.string.recording_options_export_external_music_dir_unavailable,
                Toast.LENGTH_SHORT).show();
        return;
    }

    File exported = new File(externalMusicDir, r.getName());
    FileChannel srcChannel = null;
    FileChannel dstChannel = null;
    try {
        srcChannel = mContext.openFileInput(r.getName()).getChannel();
        dstChannel = new FileOutputStream(exported).getChannel();

        srcChannel.transferTo(0, srcChannel.size(), dstChannel);

        Toast.makeText(mContext, R.string.recording_options_export_complete, Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Log.e(TAG, "onExport: Failed to export file: " + r.getName());
        e.printStackTrace();
        Toast.makeText(mContext, R.string.recording_options_export_copy_error, Toast.LENGTH_SHORT).show();
    } finally {
        try {
            if (srcChannel != null) {
                srcChannel.close();
            }
            if (dstChannel != null) {
                dstChannel.close();
            }
        } catch (IOException e) {
            // Do nothing
        }
    }
}

From source file:org.gnucash.android.export.ExportAsyncTask.java

/**
 * Moves a file from <code>src</code> to <code>dst</code>
 * @param src Absolute path to the source file
 * @param dst Absolute path to the destination file
 * @throws IOException if the file could not be moved.
 *//*from w  ww.j  a  v a  2  s  .  c o  m*/
public void moveFile(String src, String dst) throws IOException {
    File srcFile = new File(src);
    File dstFile = new File(dst);
    FileChannel inChannel = new FileInputStream(srcFile).getChannel();
    FileChannel outChannel = new FileOutputStream(dstFile).getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        outChannel.close();
    }
    srcFile.delete();
}

From source file:it.readbeyond.minstrel.commander.Commander.java

private void copyFile(String sourcePath, String destinationPath, final CallbackContext callbackContext) {
    String source = this.normalizePath(sourcePath);
    String destination = this.normalizePath(destinationPath);
    try {/*w  w w. j  av  a 2s  . com*/
        File f = new File(source);
        if (f.exists()) {
            File d = new File(destination);

            // create parent directory, if not existing
            File destinationParent = d.getParentFile();
            destinationParent.mkdirs();

            // TODO check for write permission?
            // copy file
            FileInputStream inStream = new FileInputStream(f);
            FileOutputStream outStream = new FileOutputStream(d);
            FileChannel inChannel = inStream.getChannel();
            FileChannel outChannel = outStream.getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            inStream.close();
            outStream.close();
            callbackContext.success(MESSAGE_FILE_COPIED);

        } else {
            callbackContext.success(MESSAGE_FILE_DOES_NOT_EXIST);
        }
    } catch (Exception e) {
        callbackContext.success(MESSAGE_ERROR_WHILE_COPYING);
    }
}

From source file:org.opennms.features.newts.converter.rrd.converter.JRobinConverter.java

public boolean moveFileSafely(final File in, final File out) throws IOException {
    FileInputStream fis = null;/* ww  w.java2s. c om*/
    FileOutputStream fos = null;
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    final File tempOut = File.createTempFile("move", ".tmp");
    try {
        fis = new FileInputStream(in);
        fos = new FileOutputStream(tempOut);
        inChannel = fis.getChannel();
        outChannel = fos.getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        try {
            if (inChannel != null)
                inChannel.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel);
        }
        try {
            if (outChannel != null)
                outChannel.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel);
        }
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis);
        }
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos);
        }
    }
    out.delete();
    if (!out.exists()) {
        tempOut.renameTo(out);
        return in.delete();
    }
    return false;
}