Example usage for java.nio.channels FileChannel close

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

Introduction

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

Prototype

public final void close() throws IOException 

Source Link

Document

Closes this channel.

Usage

From source file:com.flexive.shared.FxFileUtils.java

/**
 * Copy a file/*  w w  w.  ja  va 2s  .co m*/
 *
 * @param source      source file
 * @param destination destination file
 * @return success
 */
public static boolean copyFile(File source, File destination) {
    FileChannel sourceChannel = null;
    FileChannel destinationChannel = null;
    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destinationChannel = new FileOutputStream(destination).getChannel();
        // don't use transferTo because it fails for large files under windows - http://bugs.sun.com/view_bug.do?bug_id=6431344
        return copyNIOChannel(sourceChannel, destinationChannel) == source.length()
                && destination.length() == source.length();
    } catch (IOException e) {
        LOG.error(e, e);
        return false;
    } finally {
        try {
            if (sourceChannel != null)
                sourceChannel.close();
        } catch (IOException e) {
            LOG.error(e);
        }
        try {
            if (destinationChannel != null)
                destinationChannel.close();
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}

From source file:com.flexive.shared.FxFileUtils.java

/**
 * Copy the content of an InputStream to a file
 *
 * @param expectedSize    expected size of the stream
 * @param sourceStream    source//from   w w  w . j a  v a2 s .  c o  m
 * @param destinationFile destination
 * @return copy was successful and sizes match
 */
public static boolean copyStream2File(long expectedSize, InputStream sourceStream, File destinationFile) {
    ReadableByteChannel sourceChannel = null;
    FileChannel destinationChannel = null;
    try {
        sourceChannel = Channels.newChannel(sourceStream);
        destinationChannel = new FileOutputStream(destinationFile).getChannel();
        return copyNIOChannel(sourceChannel, destinationChannel) == expectedSize
                && destinationFile.length() == expectedSize;
    } catch (IOException e) {
        LOG.error(e, e);
        return false;
    } finally {
        try {
            if (sourceChannel != null)
                sourceChannel.close();
        } catch (IOException e) {
            LOG.error(e);
        }
        try {
            if (destinationChannel != null)
                destinationChannel.close();
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}

From source file:com.kactech.otj.Utils.java

public static byte[] readBytes(File f) throws IOException {
    FileInputStream fis = new FileInputStream(f);
    FileChannel fChannel = fis.getChannel();
    byte[] barray = new byte[(int) f.length()];
    ByteBuffer bb = ByteBuffer.wrap(barray);
    //bb.order(ByteOrder.LITTLE_ENDIAN);
    fChannel.read(bb);/*from w  ww.j a  v  a  2s .  co  m*/
    fChannel.close();
    fis.close();
    return bb.array();
}

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

public static void writeFile(String pathName, byte[] bytes) throws IOException {
    File fl = new File(pathName);
    if (existFile(pathName)) {
        fl.delete();/*ww  w .j a  va 2s.com*/
    }
    ByteBuffer bb = ByteBuffer.allocate(bytes.length);
    bb.put(bytes);
    bb.flip();
    FileChannel fileChannel = null;
    try {
        fileChannel = new FileOutputStream(pathName, false).getChannel();
        fileChannel.write(bb);
    } finally {
        if (fileChannel != null) {
            try {
                fileChannel.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

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

/**
 * Return the concatenation of the SHA-1 hashes of a file's pieces.
 *
 * <p>/* ww w .  ja  v  a  2s . com*/
 * 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:org.jab.docsearch.utils.FileUtils.java

/**
 * Copy file/*from ww  w .  j ava 2 s.c om*/
 *
 * @param sourceFilename       source file
 * @param destinationFilename  destination file
 */
public static boolean copyFile(String sourceFilename, String destinationFilename) {
    if (sourceFilename == null) {
        logger.warn("copyFile() failed because sourceFilename is null");
        return false;
    }
    if (destinationFilename == null) {
        logger.warn("copyFile() failed because destinationFilename is null");
        return false;
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel fcin = null;
    FileChannel fcout = null;
    try {
        // open stream and channel from input
        fis = new FileInputStream(sourceFilename);
        fcin = fis.getChannel();

        // open stream and channel from output
        fos = new FileOutputStream(destinationFilename);
        fcout = fos.getChannel();

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

        return true;
    } catch (IOException ioe) {
        logger.fatal("copyFile() failed", ioe);
        return false;
    } catch (SecurityException se) {
        logger.fatal("copyFile() failed", se);
        return false;
    } finally {
        try {
            if (fcin != null) {
                fcin.close();
            }
        } catch (IOException ioe) {
            logger.fatal("copyFile() can't close FileChannel");
        }

        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException ioe) {
            logger.fatal("copyFile() can't close FileInputStream");
        }

        try {
            if (fcout != null) {
                fcout.close();
            }
        } catch (IOException ioe) {
            logger.fatal("copyFile() can't close FileChannel");
        }

        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException ioe) {
            logger.fatal("copyFile() can't close FileOutputStream");
        }
    }
}

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

/**
 * Copy a file from one location to another.
 * <p>/*from w  w w.j  a  v a2 s  .  co  m*/
 * 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;
        }
    }
}

From source file:org.geoserver.rest.util.IOUtils.java

/**
 * Copy the input file onto the output file using the specified buffer size.
 * /*  w ww. ja va  2 s .c o m*/
 * @param sourceFile the {@link File} to copy from.
 * @param destinationFile the {@link File} to copy to.
 * @param size buffer size.
 * @throws IOException in case something bad happens.
 */
public static void copyFile(File sourceFile, File destinationFile, int size) throws IOException {
    inputNotNull(sourceFile, destinationFile);
    if (!sourceFile.exists() || !sourceFile.canRead() || !sourceFile.isFile())
        throw new IllegalStateException("Source is not in a legal state.");
    if (!destinationFile.exists()) {
        destinationFile.createNewFile();
    }
    if (destinationFile.getAbsolutePath().equalsIgnoreCase(sourceFile.getAbsolutePath()))
        throw new IllegalArgumentException("Cannot copy a file on itself");

    FileChannel source = null;
    FileChannel destination = null;
    source = new RandomAccessFile(sourceFile, "r").getChannel();
    destination = new RandomAccessFile(destinationFile, "rw").getChannel();
    try {
        copyFileChannel(size, source, destination);
    } finally {
        try {
            if (source != null) {
                try {
                    source.close();
                } catch (Throwable t) {
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.log(Level.INFO, t.getLocalizedMessage(), t);
                }
            }
        } finally {
            if (destination != null) {
                try {
                    destination.close();
                } catch (Throwable t) {
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.log(Level.INFO, t.getLocalizedMessage(), t);
                }
            }
        }
    }
}

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffReader.java

public static boolean isMMMultipageTiff(String directory) throws IOException {
    File dir = new File(directory);
    File[] children = dir.listFiles();
    File testFile = null;/*from w w w.j a va  2s  .com*/
    for (File child : children) {
        if (child.isDirectory()) {
            File[] grandchildren = child.listFiles();
            for (File grandchild : grandchildren) {
                if (grandchild.getName().endsWith(".tif")) {
                    testFile = grandchild;
                    break;
                }
            }
        } else if (child.getName().endsWith(".tif") || child.getName().endsWith(".TIF")) {
            testFile = child;
            break;
        }
    }
    if (testFile == null) {
        throw new IOException("Unexpected file structure: is this an MM dataset?");
    }
    RandomAccessFile ra;
    try {
        ra = new RandomAccessFile(testFile, "r");
    } catch (FileNotFoundException ex) {
        ReportingUtils.logError(ex);
        return false;
    }
    FileChannel channel = ra.getChannel();
    ByteBuffer tiffHeader = ByteBuffer.allocate(36);
    ByteOrder bo;
    channel.read(tiffHeader, 0);
    char zeroOne = tiffHeader.getChar(0);
    if (zeroOne == 0x4949) {
        bo = ByteOrder.LITTLE_ENDIAN;
    } else if (zeroOne == 0x4d4d) {
        bo = ByteOrder.BIG_ENDIAN;
    } else {
        throw new IOException("Error reading Tiff header");
    }
    tiffHeader.order(bo);
    int summaryMDHeader = tiffHeader.getInt(32);
    channel.close();
    ra.close();
    if (summaryMDHeader == MultipageTiffWriter.SUMMARY_MD_HEADER) {
        return true;
    }
    return false;
}

From source file:com.imaginea.kodebeagle.base.util.Utils.java

public void forceWrite(final String contents, final File file) throws IOException {
    try (FileOutputStream s = new FileOutputStream(file.getAbsolutePath(), false)) {
        s.write(contents.getBytes(StandardCharsets.UTF_8.name()));
        FileChannel c = s.getChannel();
        c.force(true);//from www .  java 2s  . c om
        s.getFD().sync();
        c.close();
        s.close();
    }
}