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:jackpal.androidterm.Term.java

private void copyClipboardToFile(String filename) {
    if (filename == null)
        return;//w  ww  .j a  v a 2  s .  c  o  m
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(filename);
        FileChannel fc = fos.getChannel();
        try {
            ClipboardManagerCompat clip = ClipboardManagerCompatFactory.getManager(getApplicationContext());
            if (clip.hasText()) {
                ByteBuffer by = ByteBuffer.wrap(clip.getText().toString().getBytes());
                fc.write(by);
            }
            fc.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:edu.cornell.med.icb.goby.modes.ConcatenateCompactReadsMode.java

/**
 * This version does a quick concat. It does NO filtering. It gathers no stats,
 * but, will quickly concat multiple compact-reads files together using NIO.
 * It should be noted that this method is >MUCH< faster.
 * Copy all of the input files except the last MessageChunksWriter.DELIMITER_LENGTH
 * bytes of the first n-1 input files and the entire last input file
 * to the output file./*from   w w w. ja  v a  2s . c o m*/
 * @throws IOException
 */
private void performQuickConcat() throws IOException {
    System.out.println("quick concatenating files");
    File outputFile = new File(outputFilename);
    if (outputFile.exists()) {
        System.err.println("The output file already exists. Please delete it before running concat.");
        return;
    }
    outputFile.createNewFile();

    FileChannel input = null;
    FileChannel output = null;
    long maxChunkSize = 10 * 1024 * 1024; // 10 megabytes at a chunk
    try {
        output = new FileOutputStream(outputFile).getChannel();
        int lastFileNumToCopy = inputFiles.size() - 1;
        int curFileNum = 0;
        for (final File inputFile : inputFiles) {
            System.out.printf("Reading from %s%n", inputFile);
            input = new FileInputStream(inputFile).getChannel();
            long bytesToCopy = input.size();
            if (curFileNum++ < lastFileNumToCopy) {
                // Compact-reads files end with a delimiter (8 x 0xff)
                // followed by a 4 byte int 0 (4 x 0x00). Strip
                // these on all but the last file.
                bytesToCopy -= (MessageChunksWriter.DELIMITER_LENGTH + 1
                        + MessageChunksWriter.SIZE_OF_MESSAGE_LENGTH);
            }

            // Copy the file about 10 megabytes at a time. It would probably
            // be marginally faster to just tell NIO to copy the ENTIRE file
            // in one go, but with very large files Java will freeze until the
            // entire chunck is copied so this makes for a more responsive program
            // should you want to ^C in the middle of the copy. Also, with the single
            // transferTo() you might not see any file size changes in the output file
            // until the entire copy is complete.
            long position = 0;
            while (position < bytesToCopy) {
                long bytesToCopyThisTime = Math.min(maxChunkSize, bytesToCopy - position);
                position += input.transferTo(position, bytesToCopyThisTime, output);
            }
            input.close();
            input = null;
        }
        System.out.printf("Concatenated %d files.%n", lastFileNumToCopy + 1);
    } finally {
        if (input != null) {
            input.close();
        }
        if (output != null) {
            output.close();
        }
    }
}

From source file:com.clustercontrol.agent.job.PublicKeyThread.java

/**
 * ?Authorized_key????<BR>/*from w  ww  . ja v a2 s . co m*/
 * 
 * @param publicKey
 * @return
 */
private synchronized boolean addKey(String publicKey) {
    m_log.debug("add key start");

    if (SKIP_KEYFILE_UPDATE) {
        m_log.info("skipped appending publicKey");
        return true;
    }

    //???
    String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH);

    m_log.debug("faileName" + fileName);
    if (fileName == null || fileName.length() == 0)
        return false;

    //File?
    File fi = new File(fileName);

    RandomAccessFile randomAccessFile = null;
    FileChannel channel = null;
    FileLock lock = null;
    boolean add = false;
    try {
        //RandomAccessFile?
        randomAccessFile = new RandomAccessFile(fi, "rw");
        //FileChannel?
        channel = randomAccessFile.getChannel();

        // 
        for (int i = 0; i < (FILELOCK_TIMEOUT / FILELOCK_WAIT); i++) {
            if (null != (lock = channel.tryLock())) {
                break;
            }
            m_log.info("waiting for locked file... [" + (i + 1) + "/" + (FILELOCK_TIMEOUT / FILELOCK_WAIT)
                    + " : " + fileName + "]");
            Thread.sleep(FILELOCK_WAIT);
        }
        if (null == lock) {
            m_log.warn("file locking timeout.");
            return false;
        }

        // (?)
        synchronized (authKeyLock) {
            //??
            channel.position(channel.size());

            //?
            String writeData = "\n" + publicKey;
            // 
            m_log.debug("add key : " + writeData);

            //?????
            ByteBuffer buffer = ByteBuffer.allocate(512);

            //???
            buffer.clear();
            buffer.put(writeData.getBytes());
            buffer.flip();
            channel.write(buffer);
        }

        add = true;
    } catch (Exception e) {
        m_log.error(e);
    } finally {
        try {
            if (channel != null) {
                channel.close();
            }
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
            if (lock != null) {
                //
                lock.release();
            }
        } catch (Exception e) {
        }
    }

    return add;
}

From source file:com.filemanager.free.filesystem.FileUtil.java

/**
 * Copy a file. The target file may even be on external SD card for Kitkat.
 *
 * @param source The source file/*from ww  w . j a  v  a  2s.  c o  m*/
 * @param target The target file
 * @return true if the copying was successful.
 */
@SuppressWarnings("null")
public static boolean copyFile(final File source, final File target, Context context) {
    FileInputStream inStream = null;
    OutputStream outStream = null;
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    try {
        inStream = new FileInputStream(source);

        // First try the normal way
        if (isWritable(target)) {
            // standard way
            outStream = new FileOutputStream(target);
            inChannel = inStream.getChannel();
            outChannel = ((FileOutputStream) outStream).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // Storage Access Framework
                DocumentFile targetDocument = getDocumentFile(target, false, context);
                outStream = context.getContentResolver().openOutputStream(targetDocument.getUri());
            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                // Workaround for Kitkat ext SD card
                Uri uri = MediaStoreHack.getUriFromFile(target.getAbsolutePath(), context);
                outStream = context.getContentResolver().openOutputStream(uri);
            } else {
                return false;
            }

            if (outStream != null) {
                // Both for SAF and for Kitkat, write to output stream.
                byte[] buffer = new byte[16384]; // MAGIC_NUMBER
                int bytesRead;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
            }

        }
    } catch (Exception e) {
        Log.e("AmazeFileUtils",
                "Error when copying file from " + source.getAbsolutePath() + " to " + target.getAbsolutePath(),
                e);
        return false;
    } finally {
        try {
            inStream.close();
        } catch (Exception e) {
            // ignore exception
        }
        try {
            outStream.close();
        } catch (Exception e) {
            // ignore exception
        }
        try {
            inChannel.close();
        } catch (Exception e) {
            // ignore exception
        }
        try {
            outChannel.close();
        } catch (Exception e) {
            // ignore exception
        }
    }
    return true;
}

From source file:com.socialmarketing.config.ApplicationPrefs.java

/**
 * Initializes preferences//from   w w  w  . jav  a  2s .  com
 *
 * @param context ServletContext
 */
public void initializePrefs(ServletContext context) {
    LOG.info("Initializing...");
    // Load the application node name, if any
    try {
        Properties instanceProperties = new Properties();
        instanceProperties.load(context.getResourceAsStream("/WEB-INF/instance.property"));
        node = instanceProperties.getProperty("node", DEFAULT_NODE);
        LOG.info("Node: " + node);
    } catch (Exception e) {
        LOG.info("Default Node: " + DEFAULT_NODE);
        node = DEFAULT_NODE;
    }
    // Determine the file library
    String fileLibrary = retrieveFileLibraryLocation(context);
    if (fileLibrary != null) {
        loadProperties(fileLibrary);
        this.add(FILE_LIBRARY_PATH, fileLibrary);
        configureDebug();
        // verifyKey(context, fileLibrary);
        // configureConnectionPool(context);
        // configureFreemarker(context);
        // configureWebdavManager(context);
        // configureSystemSettings(context);
        // configureCache(context);
        if (isConfigured()) {
            if (ApplicationVersion.isOutOfDate(this)) {
                LOG.info("Upgrade triggered... obtaining lock to continue");
                // Use a lock file to to start upgrading
                File upgradeLockFile = new File(fileLibrary + "upgrade.lock");
                FileChannel fileChannel = null;
                FileLock fileLock = null;
                try {
                    // Configure the file for locking
                    fileChannel = new RandomAccessFile(upgradeLockFile, "rw").getChannel();
                    // Use fileChannel.lock which blocks until the lock is obtained
                    fileLock = fileChannel.lock();
                    // Reload the prefs to make sure the upgrade isn't already complete
                    loadProperties(fileLibrary);
                    if (ApplicationVersion.isOutOfDate(this)) {
                        // The application needs an update
                        LOG.info("Installed version " + ApplicationVersion.getInstalledVersion(this)
                                + " will be upgraded to " + ApplicationVersion.VERSION);
                        //         performUpgrade(context);
                    }
                } catch (Exception e) {
                    LOG.error("initializePrefs-> performUpgrade", e);
                } finally {
                    try {
                        if (fileLock != null) {
                            fileLock.release();
                        }
                        if (fileChannel != null) {
                            fileChannel.close();
                        }
                    } catch (Exception eclose) {
                        LOG.error("initializePrefs-> lock", eclose);
                    }
                }
            }
            if (!ApplicationVersion.isOutOfDate(this)) {
                // Start the services now that everything is ready
                initializeServices(context);
            }
        }
    }
    configureDefaultBehavior(context);
    loadApplicationDictionaries(context);
}

From source file:com.vegnab.vegnab.MainVNActivity.java

public void copyFile(File src, File dst) throws IOException {
    FileInputStream in = new FileInputStream(src);
    FileOutputStream out = new FileOutputStream(dst);
    FileChannel fromChannel = null, toChannel = null;
    try {//from  www.  j  a  va2s .  co m
        fromChannel = in.getChannel();
        toChannel = out.getChannel();
        fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } finally {
        if (fromChannel != null)
            fromChannel.close();
        if (toChannel != null)
            toChannel.close();
    }
    in.close();
    out.close();
    // must do following or file is not visible externally
    MediaScannerConnection.scanFile(getApplicationContext(), new String[] { dst.getAbsolutePath() }, null,
            null);
}

From source file:com.splout.db.dnode.Fetcher.java

/**
 * In case of interrupted, written file is not deleted.
 *//*from  w  w  w .  j  a v  a 2 s  .  c  o m*/
private void copyFile(File sourceFile, File destFile, Reporter reporter)
        throws IOException, InterruptedException {
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;

    Throttler throttler = new Throttler((double) bytesPerSecThrottle);

    FileInputStream iS = null;
    FileOutputStream oS = null;

    try {
        iS = new FileInputStream(sourceFile);
        oS = new FileOutputStream(destFile);
        source = iS.getChannel();
        destination = oS.getChannel();
        long bytesSoFar = 0;
        long reportingBytesSoFar = 0;
        long size = source.size();

        int transferred = 0;

        while (bytesSoFar < size) {
            // Needed to being able to be interrupted at any moment.
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            // Casting to int here is safe since we will transfer at most "downloadBufferSize" bytes.
            // This is done on purpose for being able to implement Throttling.
            transferred = (int) destination.transferFrom(source, bytesSoFar, downloadBufferSize);
            bytesSoFar += transferred;
            reportingBytesSoFar += transferred;
            throttler.incrementAndThrottle(transferred);
            if (reportingBytesSoFar >= bytesToReportProgress) {
                reporter.progress(reportingBytesSoFar);
                reportingBytesSoFar = 0l;
            }
        }

        if (reporter != null) {
            reporter.progress(reportingBytesSoFar);
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (iS != null) {
            iS.close();
        }
        if (oS != null) {
            oS.close();
        }
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:semlink.apps.uvig.Generator.java

/**
 * Performs a low-level copy of one file into another.
 *
 * @param src  the source file/*from w w  w . ja v  a  2  s  . co  m*/
 * @param dest the destination file
 * @see        uvi.Generator#copySupplementalFiles()
 */
private static void copyFile(File src, File dest) {
    try {
        FileChannel sourceChannel = new FileInputStream(src).getChannel();
        FileChannel destinationChannel = new FileOutputStream(dest).getChannel();

        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);

        sourceChannel.close();
        destinationChannel.close();
    } catch (Exception e) {
        eprintln("ERROR: Problem copying image file  \"" + src.getName() + "\" to output directory.  "
                + e.getMessage());
    }
}

From source file:com.thoughtworks.go.config.GoConfigDataSource.java

public synchronized GoConfigSaveResult writeWithLock(UpdateConfigCommand updatingCommand,
        GoConfigHolder configHolder) {//from   www  .  java 2s  . c  o  m
    FileChannel channel = null;
    FileOutputStream outputStream = null;
    FileLock lock = null;
    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw");
        channel = randomAccessFile.getChannel();
        lock = channel.lock();

        // Need to convert to xml before we try to write it to the config file.
        // If our cruiseConfig fails XSD validation, we don't want to write it incorrectly.
        String configAsXml = getModifiedConfig(updatingCommand, configHolder);

        randomAccessFile.seek(0);
        randomAccessFile.setLength(0);
        outputStream = new FileOutputStream(randomAccessFile.getFD());
        LOGGER.info(String.format("[Configuration Changed] Saving updated configuration."));
        IOUtils.write(configAsXml, outputStream);
        ConfigSaveState configSaveState = shouldMergeConfig(updatingCommand, configHolder)
                ? ConfigSaveState.MERGED
                : ConfigSaveState.UPDATED;
        return new GoConfigSaveResult(internalLoad(configAsXml, getConfigUpdatingUser(updatingCommand)),
                configSaveState);
    } catch (ConfigFileHasChangedException e) {
        LOGGER.warn("Configuration file could not be merged successfully after a concurrent edit: "
                + e.getMessage(), e);
        throw e;
    } catch (GoConfigInvalidException e) {
        LOGGER.warn("Configuration file is invalid: " + e.getMessage(), e);
        throw bomb(e.getMessage(), e);
    } catch (Exception e) {
        LOGGER.error("Configuration file is not valid: " + e.getMessage(), e);
        throw bomb(e.getMessage(), e);
    } finally {
        if (channel != null && lock != null) {
            try {
                lock.release();
                channel.close();
                IOUtils.closeQuietly(outputStream);
            } catch (IOException e) {
                LOGGER.error("Error occured when releasing file lock and closing file.", e);
            }
        }
        LOGGER.debug("[Config Save] Done writing with lock");
    }
}

From source file:com.alu.e3.logger.LogCollector.java

/**
 * Copy a file from one location to another on the localhost, first moving
 * (renaming) the source file out of the way of any rotator process, and
 * then optionally deleting the source file after a successful copy.  
 * Will attempt to replicate the modification time from the original file.
 * //from w  ww  .  j av a  2  s  . c  o m
 * @param sourceFile   File to copy
 * @param destFile      Destination file
 * @param deleteSource   If <code>true</code>, will delete original after copy
 * @return            The number of bytes copied
 * @throws IOException
 */
public static long copyLocalFile(File sourceFile, File destFile, boolean deleteSource) throws IOException {
    long bytesCopied = 0L;

    if ((sourceFile == null) || (destFile == null)) {
        throw new NullPointerException(
                "Source or destination file is null (source: " + sourceFile + ", dest: " + destFile + ")");
    }

    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    String origSourcePath = sourceFile.getPath();
    File tempFile = new File(tempNameForSourceFile(sourceFile.getPath()));
    FileChannel source = null;
    FileChannel destination = null;
    IOException cleanupException = null;
    boolean success = false;

    // Copy and validate result
    try {
        // Rename source file to temporary name before copying
        if (logger.isDebugEnabled()) {
            logger.debug("Renaming local file to: {}", tempFile.getPath());
        }
        if (!sourceFile.renameTo(tempFile)) {
            logger.error("Could not move file to new name: {}", tempFile.getAbsolutePath());
        } else {
            source = new FileInputStream(tempFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            bytesCopied = destination.transferFrom(source, 0, source.size());
            copyModificationTime(tempFile, destFile);

            // Check integrity of copy
            success = validateFileCopy(tempFile, destFile);
            if (!success) {
                logger.warn("Copy of file {} did not pass integrity check!", origSourcePath);
            }
        }
    } catch (IOException ex) {
        // If there's been an error copying the file, we may be left with a zero-length or incomplete file
        if (!success) {
            if (logger.isDebugEnabled()) {
                logger.debug("Deleting failed copy of local file: {}", destFile.getAbsolutePath());
            }
            destFile.delete();
        }
    } finally {
        // Use a try-block during cleanup, but only throw exception if the
        // main file-copy try-block doesn't
        try {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
            if (deleteSource && success) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Deleting local source file: {}", tempFile.getAbsolutePath());
                }
                tempFile.delete();
            } else {
                // Move source file back from temp name
                if (tempFile == null || !tempFile.renameTo(new File(origSourcePath))) {
                    logger.error("Could not restore original filename: {}", origSourcePath);
                }
            }
        } catch (IOException ex) {
            logger.warn("IOException during local file-copy cleanup: {}", ex);
            cleanupException = new IOException(ex);
        }
    }

    if (cleanupException != null) {
        throw cleanupException;
    }
    return bytesCopied;
}