Example usage for java.nio.channels FileChannel size

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

Introduction

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

Prototype

public abstract long size() throws IOException;

Source Link

Document

Returns the current size of this channel's file.

Usage

From source file:log4JToXml.xmlToProperties.XmlToLog4jConverterImpl.java

private static void copyFile(File sourceFile, File destFile) throws IOException {

    FileChannel source = null;
    FileChannel destination = null;

    try {//ww  w.  j av  a  2  s  .  com
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:com.parse.ParseFileUtils.java

/**
 * Internal copy file method.// w  w  w. j  av  a 2 s.  co 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.liferay.util.FileUtil.java

public static void copyFile(File source, File destination, boolean hardLinks) {
    if (!source.exists()) {
        return;/*  w w  w  . ja  v  a 2s.  com*/
    }

    if (hardLinks && !Config.getBooleanProperty("CONTENT_VERSION_HARD_LINK", true)) {
        hardLinks = false;
    }

    if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) {

        destination.getParentFile().mkdirs();
    }

    if (hardLinks) {
        // I think we need to be sure to unlink first
        if (destination.exists()) {
            JNALibrary.unlink(destination.getAbsolutePath());
        }

        try {
            JNALibrary.link(source.getAbsolutePath(), destination.getAbsolutePath());
            // setting this means we will try again if we cannot hard link
            if (!destination.exists()) {
                hardLinks = false;
            }
        } catch (IOException e) {
            Logger.error(FileUtil.class, "Can't create hardLink. source: " + source.getAbsolutePath()
                    + ", destination: " + destination.getAbsolutePath());
            // setting this means we will try again if we cannot hard link
            hardLinks = false;
        }

    }
    if (!hardLinks) {
        try {
            FileChannel srcChannel = new FileInputStream(source).getChannel();
            FileChannel dstChannel = new FileOutputStream(destination).getChannel();

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

            srcChannel.close();
            dstChannel.close();
        } catch (IOException ioe) {
            Logger.error(FileUtil.class, ioe.getMessage(), ioe);
        }
    }

}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

public static void copyFile(File src, File dst) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();

    try {//from  ww w  .  ja v  a  2 s  .  c om
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}

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.j  a  v  a 2s . 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;
}

From source file:com.turn.ttorrent.common.TorrentCreator.java

/**
 * Return the concatenation of the SHA-1 hashes of a file's pieces.
 *
 * <p>/*www .j  a va  2  s .  c  om*/
 * Hashes the given file piece by piece using the default Torrent piece
 * length (see {@link #PIECE_LENGTH}) and returns the concatenation of
 * these hashes, as a string.
 * </p>
 *
 * <p>
 * This is used for creating Torrent meta-info structures from a file.
 * </p>
 *
 * @param file The file to hash.
 */
public /* for testing */ static byte[] hashFiles(Executor executor, List<File> files, long nbytes,
        int pieceLength) throws InterruptedException, IOException {
    int npieces = (int) Math.ceil((double) nbytes / pieceLength);
    byte[] out = new byte[Torrent.PIECE_HASH_SIZE * npieces];
    CountDownLatch latch = new CountDownLatch(npieces);

    ByteBuffer buffer = ByteBuffer.allocate(pieceLength);

    long start = System.nanoTime();
    int piece = 0;
    for (File file : files) {
        logger.info("Hashing data from {} ({} pieces)...",
                new Object[] { file.getName(), (int) Math.ceil((double) file.length() / pieceLength) });

        FileInputStream fis = FileUtils.openInputStream(file);
        FileChannel channel = fis.getChannel();
        int step = 10;

        try {
            while (channel.read(buffer) > 0) {
                if (buffer.remaining() == 0) {
                    buffer.flip();
                    executor.execute(new ChunkHasher(out, piece, latch, buffer));
                    buffer = ByteBuffer.allocate(pieceLength);
                    piece++;
                }

                if (channel.position() / (double) channel.size() * 100f > step) {
                    logger.info("  ... {}% complete", step);
                    step += 10;
                }
            }
        } finally {
            channel.close();
            fis.close();
        }
    }

    // Hash the last bit, if any
    if (buffer.position() > 0) {
        buffer.flip();
        executor.execute(new ChunkHasher(out, piece, latch, buffer));
        piece++;
    }

    // Wait for hashing tasks to complete.
    latch.await();
    long elapsed = System.nanoTime() - start;

    logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.",
            new Object[] { files.size(), nbytes, piece, npieces, String.format("%.1f", elapsed / 1e6) });

    return out;
}

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  va  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:org.mule.util.FileUtils.java

/** 
 * Try to move a file by renaming with backup attempt by copying/deleting via NIO.
 * Creates intermidiate directories as required.
 *//*  w  w  w . j a v  a2s.com*/
public static boolean moveFileWithCopyFallback(File sourceFile, File destinationFile) {
    // try fast file-system-level move/rename first
    boolean success = sourceFile.renameTo(destinationFile);

    if (!success) {
        // try again using NIO copy
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(sourceFile);
            if (!destinationFile.exists()) {
                FileUtils.createFile(destinationFile.getPath());
            }
            fos = new FileOutputStream(destinationFile);
            FileChannel srcChannel = fis.getChannel();
            FileChannel dstChannel = fos.getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
            success = sourceFile.delete();
        } catch (IOException ioex) {
            // grr!
            success = false;
        } finally {
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(fos);
        }
    }

    return success;
}

From source file:com.ah.ui.actions.home.clientManagement.service.CertificateGenSV.java

@SuppressWarnings("resource")
public static byte[] readFromFile(File file) throws IOException {
    FileChannel fileChannel = new FileInputStream(file).getChannel();
    ByteBuffer bb = ByteBuffer.allocate((int) fileChannel.size());
    fileChannel.read(bb);/*from   w  ww .jav  a  2 s  .  c  o m*/
    fileChannel.close();
    bb.flip();
    byte[] bytes;

    if (bb.hasArray()) {
        bytes = bb.array();
    } else {
        bytes = new byte[bb.limit()];
        bb.get(bytes);
    }

    return bytes;
}

From source file:org.xwoot.xwootUtil.FileUtil.java

/**
 * Copy a file from one location to another.
 * <p>/* w ww  .  j a v  a  2s  .c  om*/
 * If the destination file exists, it will be overridden.
 * 
 * @param sourceFile the file to copy from.
 * @param destinationFile the file to copy to.
 * @throws IOException if the sourceFilePath is not found or other IO problems occur.
 */
public static void copyFile(File sourceFile, File destinationFile) throws IOException {
    // check destination.
    FileUtil.checkDirectoryPath(destinationFile.getParentFile());

    // do the actual copy
    FileChannel sourceChannel = null;
    FileChannel destinationChannel = null;
    try {
        sourceChannel = new FileInputStream(sourceFile).getChannel();
        destinationChannel = new FileOutputStream(destinationFile).getChannel();

        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (sourceChannel != null) {
                sourceChannel.close();
            }
            if (destinationChannel != null) {
                destinationChannel.close();
            }
        } catch (IOException e) {
            throw e;
        }
    }
}