Example usage for java.io FileOutputStream getChannel

List of usage examples for java.io FileOutputStream getChannel

Introduction

In this page you can find the example usage for java.io FileOutputStream getChannel.

Prototype

public FileChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.FileChannel FileChannel object associated with this file output stream.

Usage

From source file:org.apache.nifi.file.FileUtils.java

public static long copyBytes(final byte[] bytes, final File destination, final boolean lockOutputFile)
        throws FileNotFoundException, IOException {
    FileOutputStream fos = null;
    FileLock outLock = null;//ww  w.ja va 2  s.  c  o m
    long fileSize = 0L;
    try {
        fos = new FileOutputStream(destination);
        final FileChannel out = fos.getChannel();
        if (lockOutputFile) {
            outLock = out.tryLock(0, Long.MAX_VALUE, false);
            if (null == outLock) {
                throw new IOException(
                        "Unable to obtain exclusive file lock for: " + destination.getAbsolutePath());
            }
        }
        fos.write(bytes);
        fos.flush();
        fileSize = bytes.length;
    } finally {
        FileUtils.releaseQuietly(outLock);
        FileUtils.closeQuietly(fos);
    }
    return fileSize;
}

From source file:org.datavaultplatform.common.io.FileCopy.java

/**
 * Internal copy file method.//from  w ww.  ja v  a  2  s  . co  m
 * 
 * @param progress  the progress tracking object
 * @param srcFile  the validated source file, must not be {@code null}
 * @param destFile  the validated destination file, must not be {@code null}
 * @param preserveFileDate  whether to preserve the file date
 * @throws IOException if an error occurs
 */
private static void doCopyFile(Progress progress, File srcFile, File destFile, boolean preserveFileDate)
        throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
            long copied = output.transferFrom(input, pos, count);
            pos += copied;
            progress.byteCount += copied;
            progress.timestamp = System.currentTimeMillis();
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }

    progress.fileCount += 1;
}

From source file:com.parse.ParseFileUtils.java

/**
 * Internal copy file method./*ww w. j  a  v  a 2  s .  c  o  m*/
 * This caches the original file length, and throws an IOException
 * if the output file length is different from the current input file length.
 * So it may fail if the file changes size.
 * It may also fail with "IllegalArgumentException: Negative size" if the input file is truncated part way
 * through copying the data and the new file size is less than the current position.
 *
 * @param srcFile  the validated source file, must not be {@code null}
 * @param destFile  the validated destination file, must not be {@code null}
 * @param preserveFileDate  whether to preserve the file date
 * @throws IOException if an error occurs
 * @throws IOException if the output file length is not the same as the input file length after the copy completes
 * @throws IllegalArgumentException "Negative size" if the file is truncated so that the size is less than the position
 */
private static void doCopyFile(final File srcFile, final File destFile, final boolean preserveFileDate)
        throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input = fis.getChannel();
        output = fos.getChannel();
        final long size = input.size(); // TODO See IO-386
        long pos = 0;
        long count = 0;
        while (pos < size) {
            final long remain = size - pos;
            count = remain > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : remain;
            final long bytesCopied = output.transferFrom(input, pos, count);
            if (bytesCopied == 0) { // IO-385 - can happen if file is truncated after caching the size
                break; // ensure we don't loop forever
            }
            pos += bytesCopied;
        }
    } finally {
        ParseIOUtils.closeQuietly(output);
        ParseIOUtils.closeQuietly(fos);
        ParseIOUtils.closeQuietly(input);
        ParseIOUtils.closeQuietly(fis);
    }

    final long srcLen = srcFile.length(); // TODO See IO-386
    final long dstLen = destFile.length(); // TODO See IO-386
    if (srcLen != dstLen) {
        throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile
                + "' Expected length: " + srcLen + " Actual: " + dstLen);
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }
}

From source file:com.opendesign.utils.CmnUtil.java

/**
 * ? /*from  ww  w  .  j  a  v  a2s .c  o m*/
 * 
 * @param oldFilePath
 * @param newFilePath
 */
public static void fileCopy(String oldFilePath, String newFilePath) {
    File oldFile = new File(oldFilePath);
    File newFile = new File(newFilePath);
    try {
        FileInputStream inputStream = new FileInputStream(oldFile);
        FileOutputStream outputStream = new FileOutputStream(newFile);
        FileChannel fcin = inputStream.getChannel();
        FileChannel fcout = outputStream.getChannel();

        long size = fcin.size();
        fcin.transferTo(0, size, fcout);

        fcout.close();
        fcin.close();
        outputStream.close();
        inputStream.close();
    } catch (Exception e) {
    }
}

From source file:com.opendesign.utils.CmnUtil.java

/**
 * ? /*w ww.  j a v a  2  s . com*/
 * 
 * @param oldFilePath
 * @param oldFileName
 * @param newFilePath
 * @param newFileName
 */
public static void fileCopy(String oldFilePath, String oldFileName, String newFilePath, String newFileName) {
    File oldFile = new File(oldFilePath, oldFileName);
    File newFile = new File(newFilePath, newFileName);
    try {
        FileInputStream inputStream = new FileInputStream(oldFile);
        FileOutputStream outputStream = new FileOutputStream(newFile);
        FileChannel fcin = inputStream.getChannel();
        FileChannel fcout = outputStream.getChannel();

        long size = fcin.size();
        fcin.transferTo(0, size, fcout);

        fcout.close();
        fcin.close();
        outputStream.close();
        inputStream.close();
    } catch (Exception e) {
    }
}

From source file:biz.bokhorst.xprivacy.Util.java

public static void copy(File src, File dst) throws IOException {
    FileInputStream inStream = null;
    try {/*ww  w.  j  av  a 2  s .co  m*/
        inStream = new FileInputStream(src);
        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(dst);
            FileChannel inChannel = inStream.getChannel();
            FileChannel outChannel = outStream.getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (outStream != null)
                outStream.close();
        }
    } finally {
        if (inStream != null)
            inStream.close();
    }
}

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;// ww w.  j  a v  a2s.co  m
    FileChannel destination = null;
    FileInputStream sourceStream = null;
    FileOutputStream destinationStream = null;
    final File destFile = new File(destFilename);
    final File sourceFile = new File(sourceFilename);
    try {
        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:net.sourceforge.kalimbaradio.androidapp.util.Util.java

public static void atomicCopy(File from, File to) throws IOException {
    FileInputStream in = null;//from   ww w . ja  va 2s.co m
    FileOutputStream out = null;
    File tmp = null;
    try {
        tmp = new File(to.getPath() + ".tmp");
        in = new FileInputStream(from);
        out = new FileOutputStream(tmp);
        in.getChannel().transferTo(0, from.length(), out.getChannel());
        out.close();
        if (!tmp.renameTo(to)) {
            throw new IOException("Failed to rename " + tmp + " to " + to);
        }
        LOG.info("Copied " + from + " to " + to);
    } catch (IOException x) {
        close(out);
        delete(to);
        throw x;
    } finally {
        close(in);
        close(out);
        delete(tmp);
    }
}

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

/**
  * Copy up to extent bytes of the source file to the destination
  *//from  www .  j  av  a 2s .  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:me.StevenLawson.TotalFreedomMod.TFM_Util.java

public static void downloadFile(String url, File output, boolean verbose) throws java.lang.Exception {
    final URL website = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(output);
    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
    fos.close();/*  ww  w. j ava  2 s  . c o m*/

    if (verbose) {
        TFM_Log.info("Downloaded " + url + " to " + output.toString() + ".");
    }
}