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.gatf.generator.core.GatfTestGeneratorMojo.java

/**
 * @param sourceFile//  www  .  j a v a2  s  .c om
 * @param destFile
 * @throws IOException Copy a file to some desired location
 */
@SuppressWarnings("resource")
public static void copyFile(File sourceFile, File destFile) throws IOException {
    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();

        // previous code: destination.transferFrom(source, 0, source.size());
        // to avoid infinite loops, should be:
        long count = 0;
        long size = source.size();
        while ((count += destination.transferFrom(source, count, size - count)) < size)
            ;
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:org.cloudata.core.commitlog.FileTransferThread.java

private void transfer(FileChannel[] channelList, SocketChannel socketChannel) {
    for (FileChannel fc : channelList) {
        try {/* w  w w. java  2  s  . c  om*/
            long numTransferred = 0;
            long pos = fc.position();
            long totalLength = fc.size() - pos;
            long count = totalLength;

            LOG.info(dirName + " start File Transfer:" + pos + "," + totalLength);
            while ((numTransferred += fc.transferTo(pos, count, socketChannel)) < totalLength) {
                pos += numTransferred;
                count -= numTransferred;
            }
            //LOG.info("End File Transfer:" + pos + "," + totalLength);
        } catch (IOException e) {
            LOG.warn("transfering file is fail due to : ", e);
        } finally {
            if (fc != null) {
                try {
                    fc.close();
                } catch (IOException e) {
                    LOG.warn("closing file is fail due to : ", e);
                }
            }
        }
    }
}

From source file:it.geosolutions.tools.io.file.IOUtils.java

/**
 * This method is responsible for checking if the input file is still being
 * written or if its available for being parsed.
 * /*  www  .ja  v a2  s. c om*/
 * <p>
 * Specifically this method tries to open up a "rw" channel on the provided
 * input file. If the file is still being written this operation fails with
 * an exception, we therefore catch this exception and sleep for
 * {@value #ATOMIC_WAIT} seconds as defined in the constant
 * {@link #ATOMIC_WAIT}.
 * 
 * <p>
 * If after having waited for {@link MAX_WAITING_TIME_FOR_LOCK} (which is
 * read from the configuration or set to the default value of
 * {@link #DEFAULT_WAITING_TIME}) we have not yet acquired the channel we
 * skip this file but we signal this situation.
 * 
 * NOTE: To make use of mandatory locks, mandatory locking must be enabled
 * both on the file system that contains the file to be locked, and on the
 * file itself. Mandatory locking is enabled on a file system using the
 * "-o mand" option to mount(8), or the MS_MANDLOCK flag for mount(2).
 * Mandatory locking is enabled on a file by disabling group execute
 * permission on the file and enabling the set-group-ID permission bit (see
 * chmod(1) and chmod(2)).
 * 
 * @param caller
 * @param inputFile
 * @param maxwait
 * @return <code>true</code> if the lock has been successfully acquired.
 *         <code>false</code> otherwise
 * @throws InterruptedException
 * @throws IOException
 */
public static boolean acquireLock(Object caller, File inputFile, final long maxwait)
        throws InterruptedException, IOException {

    if (!inputFile.exists())
        return false;// file not exists!

    if (inputFile.isDirectory()) {
        // return inputFile.setReadOnly();
        return true;// cannot lock directory
    }

    // //
    //
    // Acquire an exclusive lock to wait for long
    // writing processes before trying to check on them
    //
    // //
    double sumWait = 0;
    while (true) {
        FileOutputStream outStream = null;
        FileChannel channel = null;
        FileLock lock = null;
        try {
            outStream = new FileOutputStream(inputFile, true);

            // get a rw channel
            channel = outStream.getChannel();
            if (channel != null) {
                // here we could block
                lock = channel.tryLock();
                if (lock != null) {
                    if (LOGGER.isTraceEnabled())
                        LOGGER.trace("File locked successfully");
                    return true;
                }
            }
        } catch (OverlappingFileLockException e) {
            // File is already locked in this thread or virtual machine
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("File is already locked in this thread or virtual machine");
        } catch (Exception e) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(e.getLocalizedMessage(), e);
        } finally {

            org.apache.commons.io.IOUtils.closeQuietly(outStream);

            // release the lock
            if (lock != null)
                try {
                    lock.release();
                } catch (Exception e) {
                    // eat me
                }

            if (channel != null)
                try {
                    channel.close();
                } catch (Exception e) {
                    // eat me
                }
        }

        // Sleep for ATOMIC_WAIT milliseconds prior to retry for acquiring
        // the lock
        synchronized (caller) {
            caller.wait(Conf.ATOMIC_WAIT);
        }

        sumWait += Conf.ATOMIC_WAIT;
        if (sumWait > maxwait) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn("Waiting time beyond maximum specified waiting time, exiting...");
            // Quitting the loop
            break;
        }
    }

    // A time greater than MAX_WAITING_TIME_FOR_LOCK has elapsed and no lock
    // has
    // been acquired. Thus, I need to return false
    return false;
}

From source file:org.codehaus.preon.buffer.DefaultBitBuffer.java

/** Read byte buffer containing binary stream and set the bit pointer position to 0. */
public DefaultBitBuffer(String fileName) {

    File file = new File(fileName);

    // Open the file and then get a org.codehaus.preon.channel.channel from the stream
    FileInputStream fis;/*from w  w  w. j ava 2 s. co  m*/

    try {
        fis = new FileInputStream(file);

        FileChannel fc = fis.getChannel();

        // Get the file's size and then map it into memory
        int fileSize = (int) fc.size();
        ByteBuffer inputByteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);

        // Close the org.codehaus.preon.channel.channel and the stream
        fc.close();

        this.byteBuffer = inputByteBuffer;
        bitBufBitSize = ((long) (inputByteBuffer.capacity())) << 3;
        bitPos = 0;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.kepler.ssh.LocalExec.java

/**
 * Copies src file to dst file. If the dst file does not exist, it is
 * created//from   w  w w  .ja v  a2 s . c om
 */
private void copyFile(File src, File dst) throws IOException {
    // see if source and destination are the same
    if (src.equals(dst)) {
        // do not copy
        return;
    }

    //System.out.println("copying " + src + " to " + dst);

    FileChannel srcChannel = new FileInputStream(src).getChannel();
    FileChannel dstChannel = new FileOutputStream(dst).getChannel();
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    srcChannel.close();
    dstChannel.close();

    /* hacking for non-windows */
    // set the permission of the target file the same as the source file
    if (_commandArr[0] == "/bin/sh") {

        String osName = StringUtilities.getProperty("os.name");
        if (osName.startsWith("Mac OS X")) {

            // chmod --reference does not exist on mac, so do the best
            // we can using the java file api
            // WARNING: this relies on the umask to set the group, world
            // permissions.
            dst.setExecutable(src.canExecute());
            dst.setWritable(src.canWrite());

        } else {

            String cmd = "chmod --reference=" + src.getAbsolutePath() + " " + dst.getAbsolutePath();
            try {
                ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
                ByteArrayOutputStream streamErr = new ByteArrayOutputStream();
                executeCmd(cmd, streamOut, streamErr);
            } catch (ExecException e) {
                log.warn("Tried to set the target file permissions the same as "
                        + "the source but the command failed: " + cmd + "\n" + e);
            }
        }
    }
}

From source file:Xtext2SonarM2T.launcher.popupMenus.AcceleoGenerateGenerateSonarQubePluginAction.java

@SuppressWarnings("resource")
private void copyFile(File source, File target, String name) throws IOException {
    if (!target.exists()) {
        target.createNewFile();/*from   w ww.  j a v  a2s.c o m*/
    }

    //updateNaming(source, name);

    FileChannel sourceChannel;
    FileChannel targetChannel;

    sourceChannel = new FileInputStream(source).getChannel();
    targetChannel = new FileOutputStream(target).getChannel();
    sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);

    if (sourceChannel != null) {
        sourceChannel.close();
    }

    if (targetChannel != null) {
        targetChannel.close();
    }
}

From source file:hornet.framework.clamav.service.ClamAVCheckService.java

/**
 * Rcupration du fichier  stream./*from  w  ww . j a v  a2  s .  c o  m*/
 *
 * @param fileForTest
 *            fichier de test
 * @param fileForTestSize
 *            taille du fichier
 * @return MappedByteBuffer
 * @throws IOException
 *             probleme de lecture
 */
protected MappedByteBuffer recupFichierStream(final File fileForTest, final long fileForTestSize)
        throws IOException {

    // Rcupration du fichier  stream
    final RandomAccessFile raf = new RandomAccessFile(fileForTest, "r");
    final FileChannel readChannel = raf.getChannel();
    MappedByteBuffer bufFile = null;
    try {
        bufFile = readChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileForTestSize);
    } finally {
        if (readChannel != null) {
            try {
                readChannel.close();
            } catch (final IOException e) {
                ClamAVCheckService.LOGGER.error("Erreur lors de la fermeture de la socket", e);
            }
        }
        if (raf != null) {
            try {
                raf.close();
            } catch (final IOException e) {
                ClamAVCheckService.LOGGER.error("Erreur lors de la fermeture de la socket", e);
            }
        }
    }
    return bufFile;
}

From source file:org.python.pydev.core.REF.java

/**
 * Copy a file from one place to another.
 * /* www  .  j  a  v  a2  s .co m*/
 * Example from: http://www.exampledepot.com/egs/java.nio/File2File.html
 * 
 * @param srcFilename the source file
 * @param dstFilename the destination
 */
public static void copyFile(String srcFilename, String dstFilename) {
    FileChannel srcChannel = null;
    FileChannel dstChannel = null;
    try {
        // Create channel on the source
        srcChannel = new FileInputStream(srcFilename).getChannel();

        // Create channel on the destination
        dstChannel = new FileOutputStream(dstFilename).getChannel();

        // Copy file contents from source to destination
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        // Close the channels
        if (srcChannel != null) {
            try {
                srcChannel.close();
            } catch (IOException e) {
                Log.log(e);
            }
        }
        if (dstChannel != null) {
            try {
                dstChannel.close();
            } catch (IOException e) {
                Log.log(e);
            }
        }
    }

}

From source file:org.talend.designer.core.ui.preferences.I18nPreferencePage.java

private void transferStream(File sourceFile, File targetFile) {
    if (!sourceFile.exists()) {
        return;/*from  w w  w . ja  va 2  s  . c  om*/
    }
    try {
        FileChannel sourceChannel = new FileInputStream(sourceFile.getAbsoluteFile()).getChannel();
        FileChannel targetChannel = new FileOutputStream(targetFile.getAbsoluteFile()).getChannel();
        targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        sourceChannel.close();
        targetChannel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.fhcrc.cpl.viewer.quant.gui.QuantitationReviewer.java

/**
 * Remove all the events the user has designated as 'bad' from the pepXML file they came from
 * TODO: report how many events weren't found
 * @param quantEvents//from   ww w.j  a  v  a 2  s. c  o m
 * @param pepXmlFile
 * @param outFile
 * @throws IOException
 * @throws XMLStreamException
 */
public static void filterBadEventsFromFile(List<QuantEvent> quantEvents, File pepXmlFile, File outFile)
        throws IOException, XMLStreamException {
    Map<String, List<Integer>> fractionBadQuantScanListMap = new HashMap<String, List<Integer>>();
    Map<String, List<Integer>> fractionBadIDScanListMap = new HashMap<String, List<Integer>>();
    Map<String, Map<Integer, Float>> fractionScanNewRatioMap = new HashMap<String, Map<Integer, Float>>();

    for (QuantEvent quantEvent : quantEvents) {
        String fraction = quantEvent.getFraction();

        if (quantEvent.getIdCurationStatus() == QuantEvent.CURATION_STATUS_BAD) {
            List<Integer> thisFractionList = fractionBadIDScanListMap.get(fraction);
            if (thisFractionList == null) {
                thisFractionList = new ArrayList<Integer>();
                fractionBadIDScanListMap.put(fraction, thisFractionList);
            }
            thisFractionList.add(quantEvent.getScan());
            for (QuantEvent otherEvent : quantEvent.getOtherEvents())
                if (!thisFractionList.contains(otherEvent.getScan()))
                    thisFractionList.add(otherEvent.getScan());
            _log.debug("Stripping ID for " + (quantEvent.getOtherEvents().size() + 1) + " events for peptide "
                    + quantEvent.getPeptide() + " from fraction " + fraction);
        }
        //only if the ID was unknown or good do we check quant -- quant is automatically
        //filtered for bad IDs
        else if (quantEvent.getQuantCurationStatus() == QuantEvent.CURATION_STATUS_BAD) {
            List<Integer> thisFractionList = fractionBadQuantScanListMap.get(fraction);
            if (thisFractionList == null) {
                thisFractionList = new ArrayList<Integer>();
                fractionBadQuantScanListMap.put(fraction, thisFractionList);
            }
            thisFractionList.add(quantEvent.getScan());
            int numOtherEvents = 0;
            if (quantEvent.getOtherEvents() != null) {
                for (QuantEvent otherEvent : quantEvent.getOtherEvents())
                    if (!thisFractionList.contains(otherEvent.getScan()))
                        thisFractionList.add(otherEvent.getScan());
                numOtherEvents = quantEvent.getOtherEvents().size();
            }
            ApplicationContext.infoMessage("Stripping Quantitation for " + (numOtherEvents + 1)
                    + " events for peptide " + quantEvent.getPeptide() + " from fraction " + fraction);
        }
        //dhmay adding 20090723
        else if (quantEvent.getQuantCurationStatus() == QuantEvent.CURATION_STATUS_RATIO_ONEPEAK) {
            Map<Integer, Float> thisFractionMap = fractionScanNewRatioMap.get(fraction);
            if (thisFractionMap == null) {
                thisFractionMap = new HashMap<Integer, Float>();
                fractionScanNewRatioMap.put(fraction, thisFractionMap);
            }
            float newRatio = quantEvent.getRatioOnePeak();
            thisFractionMap.put(quantEvent.getScan(), newRatio);
            for (QuantEvent otherEvent : quantEvent.getOtherEvents())
                if (!thisFractionMap.containsKey(otherEvent.getScan()))
                    thisFractionMap.put(otherEvent.getScan(), newRatio);
            ApplicationContext.infoMessage(
                    "Changing ratios to " + newRatio + " for " + (quantEvent.getOtherEvents().size() + 1)
                            + " events for peptide " + quantEvent.getPeptide() + " from fraction " + fraction);
        }
    }
    ApplicationContext.infoMessage("OK, decided what to do.  Now to strip the IDs from the pepXML file....");
    File actualOutFile = outFile;
    String dummyOwner = "DUMMY_OWNER_QURATE_STRIP";
    boolean sameInputAndOutput = pepXmlFile.getAbsolutePath().equals(outFile.getAbsolutePath());
    if (sameInputAndOutput)
        actualOutFile = TempFileManager.createTempFile("temp_quratestrip_" + outFile.getName(), dummyOwner);

    StripQuantOrIDPepXmlRewriter quantStripper = new StripQuantOrIDPepXmlRewriter(pepXmlFile, actualOutFile,
            fractionBadIDScanListMap, fractionBadQuantScanListMap, fractionScanNewRatioMap);
    quantStripper.rewrite();
    quantStripper.close();
    if (sameInputAndOutput) {
        //file-copying.  Java 1.6 still doesn't have a reasonable and concise way to do it.
        FileChannel inChannel = new FileInputStream(actualOutFile).getChannel();
        FileChannel outChannel = new FileOutputStream(outFile).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
        TempFileManager.deleteTempFiles(dummyOwner);
    }
    ApplicationContext.infoMessage("Done!  Saved stripped file to " + outFile.getAbsolutePath());
}