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:at.ac.tuwien.infosys.util.ImageUtil.java

private void saveFile(URL url, Path file) throws IOException {
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileChannel channel = FileChannel.open(file, EnumSet.of(StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE));
    channel.transferFrom(rbc, 0, Long.MAX_VALUE);
    channel.close();
}

From source file:net.librec.util.FileUtil.java

/**
 * fast file copy//from www  .  ja va  2s .  c  om
 *
 * @param source source file
 * @param target target file
 * @throws Exception if error occurs
 */
public static void copyFile(File source, File target) throws Exception {

    FileInputStream fis = new FileInputStream(source);
    FileOutputStream fos = new FileOutputStream(target);
    FileChannel inChannel = fis.getChannel();
    FileChannel outChannel = fos.getChannel();

    // inChannel.transferTo(0, inChannel.size(), outChannel);
    // original -- apparently has trouble copying large files on Windows

    // magic number for Windows, 64Mb - 32Kb
    int maxCount = (64 * 1024 * 1024) - (32 * 1024);
    long size = inChannel.size();
    long position = 0;
    while (position < size) {
        position += inChannel.transferTo(position, maxCount, outChannel);
    }

    inChannel.close();
    outChannel.close();
    fis.close();
    fos.close();
}

From source file:hk.hku.cecid.corvus.http.EnvelopQuerySender.java

/**
 * [@EVENT] This method is invoked when received the reply HTTP  response from the server.
 * <br/><br/>/*from w w  w .ja  v  a 2 s  .c om*/
 * It saves the response body stream and then available to get through by {@link #getEnvelopStream()}
 */
protected void onResponse() throws Exception {
    HttpMethod post = this.getExecutedMethod();
    InputStream ins = post.getResponseBodyAsStream();

    /*
     * We have to pipe the content to either memory or storage because the response stream
     * is directly extracted from socket which is going to close upon the connection 
     * has been closed.
     */
    if (ins.available() < THRESHOLD) {
        byte[] envelop = IOHandler.readBytes(ins);
        this.envelopStream = new ByteArrayInputStream(envelop);
    } else {
        // Create a temporary file at TMP directory.
        File envelopTmp = new File(BASE_PATH + this.hashCode());
        envelopTmp.deleteOnExit();
        // Pipe the content to the TMP file.
        FileChannel fChannel = new FileInputStream(envelopTmp).getChannel();
        fChannel.transferFrom(Channels.newChannel(ins), 0, ins.available());
        fChannel.close();
        // Create an buffered stream to the file.
        this.envelopStream = new BufferedInputStream(new FileInputStream(envelopTmp));
        // InputStream is closed automatically.
    }
}

From source file:edu.stanford.epad.common.util.EPADFileUtils.java

public static File copyFile(File src, File dst) {
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    try {// w  w  w.  j  a  v a 2 s  .c  o m
        inChannel = new FileInputStream(src).getChannel();
        outChannel = new FileOutputStream(dst).getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
        return dst;
    } catch (Exception e) {
        log.warning("Error copying file, from " + src.getAbsolutePath() + " to " + dst.getAbsolutePath(), e);
    } finally {
        try {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        } catch (IOException e) {
        }
    }
    return null;
}

From source file:org.openmrs.module.formentry.FormEntryUtil.java

/**
 * Generates an expanded 'starter XSN'. This starter is essentially a blank XSN template to play
 * with in Infopath. Should be used similar to
 * <code>org.openmrs.module.formentry.FormEntryUtil.expandXsnContents(java.lang.String)</code>
 * Generates an expanded 'starter XSN'. This starter is essentially a blank XSN template to play
 * with in Infopath. Should be used similar to
 * <code>org.openmrs.formentry.FormEntryUtil.expandXsnContents(java.lang.String)</code>
 * //from  www  .j  a v  a 2  s .  c om
 * @return File directory holding blank xsn contents
 * @throws IOException
 */
public static File getExpandedStarterXSN() throws IOException {

    // temp directory to hold the new xsn contents
    File tempDir = FormEntryUtil.createTempDirectory("XSN-starter");
    if (tempDir == null)
        throw new IOException("Failed to create temporary directory");

    // iterate over and copy each file in the given folder
    File starterDir = getResourceFile(FormEntryConstants.FORMENTRY_STARTER_XSN_FOLDER_PATH);
    for (File f : starterDir.listFiles()) {
        File newFile = new File(tempDir, f.getName());
        FileChannel in = null, out = null;
        try {
            in = new FileInputStream(f).getChannel();
            out = new FileOutputStream(newFile).getChannel();
            in.transferTo(0, in.size(), out);
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }

    return tempDir;
}

From source file:ar.com.init.agros.license.LicenseVerifier.java

public void installLicense(String file) throws Exception {

    File licenseFile = new File(file);
    if (!isMasterLicense(file)) {
        licenseManager = new LicenseManager(createLicenseParam());
        licenseManager.install(licenseFile);
    } else {/*from   ww w.j  av  a2 s.  c  o m*/
        logger.fine("Using master license");
    }
    File installedFile = new File(INSTALLED_LICENSE_FILE);

    if (!installedFile.exists()) {
        FileChannel in = (new FileInputStream(licenseFile)).getChannel();
        FileChannel out = (new FileOutputStream(installedFile)).getChannel();
        in.transferTo(0, licenseFile.length(), out);
        in.close();
        out.close();
    }
}

From source file:forge.gui.ImportDialog.java

private static void _copyFile(final File srcFile, final File destFile, final boolean deleteSrcAfter)
        throws IOException {
    destFile.getParentFile().mkdirs();//from   w  w w  . j  a v a  2 s . com

    // if this is a move, try a simple rename first
    if (deleteSrcAfter) {
        if (srcFile.renameTo(destFile)) {
            return;
        }
    }

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

    FileChannel src = null;
    FileChannel dest = null;
    try {
        src = new FileInputStream(srcFile).getChannel();
        dest = new FileOutputStream(destFile).getChannel();
        dest.transferFrom(src, 0, src.size());
    } finally {
        if (src != null) {
            src.close();
        }
        if (dest != null) {
            dest.close();
        }
    }

    if (deleteSrcAfter) {
        srcFile.delete();
    }
}

From source file:ar.com.init.agros.license.LicenseVerifier.java

private boolean isMasterLicense(String file) throws IOException, FileNotFoundException {
    File licenseFile = new File(file);
    FileChannel fc = (new FileInputStream(licenseFile)).getChannel();
    byte[] bytes = new byte[(int) fc.size()];
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    fc.read(bb);/*www . j  av a 2 s. c o  m*/
    String hash = DigestUtils.md5Hex(bytes);
    fc.close();
    boolean isMaster = hash.equals(MASTER_LICENSE_HASH);
    return isMaster;
}

From source file:com.thinkberg.vfs.s3.jets3t.Jets3tFileObject.java

protected InputStream doGetInputStream() throws Exception {
    if (!contentCached) {
        object = service.getObject(bucket, getS3Key());
        LOG.debug(String.format("caching content of '%s'", object.getKey()));

        InputStream objectInputStream = object.getDataInputStream();
        if (object.getContentLength() > 0) {
            ReadableByteChannel rbc = Channels.newChannel(objectInputStream);
            FileChannel cacheFc = getCacheFile().getChannel();
            cacheFc.transferFrom(rbc, 0, object.getContentLength());
            cacheFc.close();
            rbc.close();//w ww .j ava2 s.com
        } else {
            objectInputStream.close();
        }
        contentCached = true;
    }

    return Channels.newInputStream(getCacheFile().getChannel());
}

From source file:org.ros.internal.message.new_style.ServiceLoader.java

private void addServiceDefinitionFromPaths(File searchPath, File servicePath, CharsetDecoder decoder)
        throws IOException {
    FileInputStream inputStream = new FileInputStream(servicePath);
    FileChannel channel = inputStream.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
    channel.read(buffer);/*  w ww. j a v a  2s.  c  o m*/
    buffer.rewind();
    decoder.reset();
    String definition = decoder.decode(buffer).toString().trim();
    serviceDefinitions.put(pathToServiceName(searchPath, servicePath), definition);
    channel.close();
    inputStream.close();
}