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:com.weihuoya.bboo._G.java

public static boolean copyFile(File src, File dst) {
    FileInputStream instream = null;
    FileOutputStream outstream = null;
    FileChannel inchannel = null;
    FileChannel outchannel = null;

    try {/*from   w w w . ja  v a 2  s  . co  m*/
        // channel
        instream = new FileInputStream(src);
        outstream = new FileOutputStream(dst);
        inchannel = instream.getChannel();
        outchannel = outstream.getChannel();
        // transfer
        inchannel.transferTo(0, inchannel.size(), outchannel);
        // close
        inchannel.close();
        outchannel.close();
        instream.close();
        outstream.close();
        //
        return true;
    } catch (IOException e) {
        _G.log(e.toString());
    }
    return false;
}

From source file:org.apache.axiom.attachments.impl.BufferUtils.java

/**
 * Opimized writing to FileOutputStream using a channel
 * @param is/*from   w w w .  j a  v  a2 s  .c o m*/
 * @param fos
 * @return false if lock was not aquired
 * @throws IOException
 */
public static boolean inputStream2FileOutputStream(InputStream is, FileOutputStream fos) throws IOException {

    // See if a file channel and lock can be obtained on the FileOutputStream
    FileChannel channel = null;
    FileLock lock = null;
    ByteBuffer bb = null;
    try {
        channel = fos.getChannel();
        if (channel != null) {
            lock = channel.tryLock();
        }
        bb = getTempByteBuffer();
    } catch (Throwable t) {
    }
    if (lock == null || bb == null || !bb.hasArray()) {
        releaseTempByteBuffer(bb);
        return false; // lock could not be set or bb does not have direct array access
    }

    try {

        // Read directly into the ByteBuffer array
        int bytesRead = is.read(bb.array());
        // Continue reading until no bytes are read and no
        // bytes are now available.
        while (bytesRead > 0 || is.available() > 0) {
            if (bytesRead > 0) {
                int written = 0;

                if (bytesRead < BUFFER_LEN) {
                    // If the ByteBuffer is not full, allocate a new one
                    ByteBuffer temp = ByteBuffer.allocate(bytesRead);
                    temp.put(bb.array(), 0, bytesRead);
                    temp.position(0);
                    written = channel.write(temp);
                } else {
                    // Write to channel
                    bb.position(0);
                    written = channel.write(bb);
                    bb.clear();
                }

            }

            // REVIEW: Do we need to ensure that bytesWritten is 
            // the same as the number of bytes sent ?

            bytesRead = is.read(bb.array());
        }
    } finally {
        // Release the lock
        lock.release();
        releaseTempByteBuffer(bb);
    }
    return true;
}

From source file:ValidateLicenseHeaders.java

/**
 * Replace a legacy jboss header with the current default header
 * //from w ww  .j  a  v a 2s  . co  m
 * @param javaFile -
 *          the java source file
 * @param endOfHeader -
 *          the offset to the end of the legacy header
 * @throws IOException -
 *           thrown on failure to replace the header
 */
static void replaceHeader(File javaFile, long endOfHeader) throws IOException {
    if (log.isLoggable(Level.FINE))
        log.fine("Replacing legacy jboss header in: " + javaFile);
    RandomAccessFile raf = new RandomAccessFile(javaFile, "rw");
    File bakFile = new File(javaFile.getAbsolutePath() + ".bak");
    FileOutputStream fos = new FileOutputStream(bakFile);
    fos.write(DEFAULT_HEADER.getBytes());
    FileChannel fc = raf.getChannel();
    long count = raf.length() - endOfHeader;
    fc.transferTo(endOfHeader, count, fos.getChannel());
    fc.close();
    fos.close();
    raf.close();
    if (javaFile.delete() == false)
        log.severe("Failed to delete java file: " + javaFile);
    if (bakFile.renameTo(javaFile) == false)
        throw new SyncFailedException("Failed to replace: " + javaFile);
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * Downloads data from the given URL and saves it to the given file
 * @param url The url to download from/*from  ww w.  j a  v a2s  . c o  m*/
 * @param file The file to save to.
 *
 * TODO: how to handle partial downloads? Old file is overwritten as soon as FileOutputStream is created.
 */
public static void downloadToFile(URL url, File file) throws IOException {
    file.getParentFile().mkdirs();
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileOutputStream fos = new FileOutputStream(file);
    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
    fos.close();
}

From source file:net.sf.firemox.xml.XmlTbs.java

/**
 * Writes a list of actions described in the given XML node to the given
 * OutputStream (which must be a FileOutputStream) prefixing the stream with
 * an integer containing the number of written actions and returns this number
 * of written actions./*from   www. j av  a  2s .  c om*/
 * 
 * @param node
 *          the node containing list of actions
 * @param out0
 *          the OutputStream to write the given actions to
 * @throws IOException
 *           if an I/O error occurs if an illegal access error occurs if a
 *           security error occurs if an illegal argument is given
 * @return the amount of written action.
 */
public static int writeActionList(Node node, OutputStream out0) throws IOException {
    assert out0 instanceof FileOutputStream;
    boolean oldDefaultOnMeTag = XmlTools.defaultOnMeTag;
    XmlTools.defaultOnMeTag = true;
    FileOutputStream out = (FileOutputStream) out0;
    int nbCost = 0;
    currentActionIndex = 0;
    if (node == null) {
        out.write(0);
    } else {
        // first, evaluate the amount of actions to write
        final long position = out.getChannel().position();
        out.write(0); // this byte will be replaced later
        nbCost += writeActionListNoNb(node, out);
        long tmpPosition = out.getChannel().position();
        out.getChannel().position(position);
        out.write(nbCost);
        out.getChannel().position(tmpPosition);
    }
    XmlTools.defaultOnMeTag = oldDefaultOnMeTag;
    return nbCost;
}

From source file:com.github.fritaly.dualcommander.Utils.java

private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }/*from w ww  . j  a  v  a 2 s  . c o m*/

    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;
            pos += output.transferFrom(input, pos, count);
        }
    } 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());
    }
}

From source file:org.eclipse.thym.core.internal.util.FileUtils.java

private static void createFileFromZipFile(File file, ZipFile zipFile, ZipEntry zipEntry) throws IOException {
    if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        throw new IOException("Can not create parent directory for " + file.toString());
    }//from  w w  w . j  a v a2 s  . c  o  m
    file.createNewFile();
    FileOutputStream fout = null;
    FileChannel out = null;
    InputStream in = null;
    try {
        fout = new FileOutputStream(file);
        out = fout.getChannel();
        in = zipFile.getInputStream(zipEntry);
        out.transferFrom(Channels.newChannel(in), 0, Integer.MAX_VALUE);
    } finally {
        if (out != null)
            out.close();
        if (in != null)
            in.close();
        if (fout != null)
            fout.close();
    }
}

From source file:eu.betaas.taas.taasvmmanager.configuration.TaaSVMMAnagerConfiguration.java

private static void downloadBaseImages() {
    URL website;/*from ww w  .ja  va 2s. com*/
    ReadableByteChannel rbc;
    FileOutputStream fos;
    logger.info("Downloading default VM images.");
    try {
        website = new URL(baseImagesURL);
        rbc = Channels.newChannel(website.openStream());
        fos = new FileOutputStream(baseImagesPath);
        logger.info("Downloading base image from " + baseImagesURL);
        //new DownloadUpdater(baseComputeImageX86Path, baseImagesURL).start();
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    } catch (MalformedURLException e) {
        logger.error("Error downloading images: bad URL.");
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error("Error downloading images: IO exception.");
        logger.error(e.getMessage());
    }
    logger.info("Completed!");
}

From source file:gov.nasa.ensemble.common.io.FileUtilities.java

/**
 * Make a copy of a file on the filesystem (platform independent).
 * //from w w  w . j  ava 2 s  .  co  m
 * @param source
 *            the file to copy.
 * @param dest
 *            the copy to make.
 * @return whether the file copy exists on the filesystem upon completion.
 * @throws IOException
 */
public static boolean copyFile(File source, File dest) throws IOException {
    FileInputStream sourceStream = new FileInputStream(source);
    FileChannel sourceChannel = sourceStream.getChannel();
    FileOutputStream destStream = new FileOutputStream(dest);
    FileChannel destChannel = destStream.getChannel();
    try {
        sourceChannel.transferTo(0, sourceChannel.size(), destChannel);
    } catch (IOException ex) {
        if (ex.getCause() instanceof OutOfMemoryError) {
            IOUtils.copy(sourceStream, destStream);
        }
    } finally {
        destChannel.close();
        IOUtils.closeQuietly(destStream);
        sourceChannel.close();
        IOUtils.closeQuietly(sourceStream);
    }

    return dest.exists();
}

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

/**
 * Copies the contents of a file into a new file in the given directory.  The new file will have the same name as
 * the original file.//w ww  . ja  va2 s.  c  o  m
 *
 * @param fromFile the file to copy
 * @param deployDirectory the directory in which to copy the file -- if this is not a directory, the new file will
 * be created with this name
 *
 * @return the File that was created
 *
 * @throws IOException if there are I/O errors during reading or writing
 */
public static File copy(final File fromFile, final File deployDirectory) throws IOException {
    // if not a directory, then just use deployDirectory as the filename for the copy
    File destination = deployDirectory;
    if (deployDirectory.isDirectory()) {
        // otherwise use original file's name
        destination = new File(deployDirectory, fromFile.getName());
    }

    FileInputStream fileInputStream = null;
    FileChannel sourceChannel = null;
    FileOutputStream fileOutputStream = null;
    FileChannel destinationChannel = null;

    try {
        //noinspection IOResourceOpenedButNotSafelyClosed
        fileInputStream = new FileInputStream(fromFile);
        //noinspection ChannelOpenedButNotSafelyClosed
        sourceChannel = fileInputStream.getChannel();

        //noinspection IOResourceOpenedButNotSafelyClosed
        fileOutputStream = new FileOutputStream(destination);
        //noinspection ChannelOpenedButNotSafelyClosed
        destinationChannel = fileOutputStream.getChannel();
        final int maxCount = (64 * 1024 * 1024) - (32 * 1024);
        final long size = sourceChannel.size();
        long position = 0;
        while (position < size) {
            position += sourceChannel.transferTo(position, maxCount, destinationChannel);
        }
    } catch (IOException ie) {
        throw new IOException("Failed to copy " + fromFile + " to " + deployDirectory + ".\n Error Details: "
                + ie.toString());
    } finally {
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(sourceChannel);
        IOUtils.closeQuietly(fileOutputStream);
        IOUtils.closeQuietly(destinationChannel);
    }

    return destination;
}