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:org.eclipse.orion.internal.server.servlets.xfer.ClientImport.java

/**
 * A put is used to send a chunk of a file.
 *//*from   w w  w. java2  s . c o m*/
void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    int transferred = getTransferred();
    int length = getLength();
    int headerLength = Integer.valueOf(req.getHeader(ProtocolConstants.HEADER_CONTENT_LENGTH));
    String rangeString = req.getHeader(ProtocolConstants.HEADER_CONTENT_RANGE);
    if (rangeString == null)
        rangeString = "bytes 0-" + (length - 1) + '/' + length; //$NON-NLS-1$
    ContentRange range = ContentRange.parse(rangeString);
    if (length != range.getLength()) {
        fail(req, resp, "Chunk specifies an incorrect document length");
        return;
    }
    if (range.getStartByte() > transferred) {
        fail(req, resp, "Chunk missing; Expected start byte: " + transferred);
        return;
    }
    if (range.getEndByte() < range.getStartByte()) {
        fail(req, resp, "Invalid range: " + rangeString);
        return;
    }
    int chunkSize = 1 + range.getEndByte() - range.getStartByte();
    if (chunkSize != headerLength) {
        fail(req, resp, "Content-Range doesn't agree with Content-Length");
        return;
    }
    byte[] chunk = readChunk(req, chunkSize);
    FileOutputStream fout = null;
    try {
        fout = new FileOutputStream(new File(getStorageDirectory(), FILE_DATA), true);
        FileChannel channel = fout.getChannel();
        channel.position(range.getStartByte());
        channel.write(ByteBuffer.wrap(chunk));
        channel.close();
    } finally {
        try {
            if (fout != null)
                fout.close();
        } catch (IOException e) {
            //ignore secondary failure
        }
    }
    transferred = range.getEndByte() + 1;
    setTransferred(transferred);
    save();
    if (transferred >= length) {
        completeTransfer(req, resp);
        return;
    }
    resp.setStatus(308);//Resume Incomplete
    resp.setHeader("Range", "bytes 0-" + range.getEndByte()); //$NON-NLS-2$
    setResponseLocationHeader(req, resp);
}

From source file:com.p2p.peercds.common.Torrent.java

private static String hashFiles(List<File> files) throws InterruptedException, IOException {
    int threads = getHashingThreadsCount();
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    ByteBuffer buffer = ByteBuffer.allocate(PIECE_LENGTH);
    List<Future<String>> results = new LinkedList<Future<String>>();
    StringBuilder hashes = new StringBuilder();

    long length = 0L;
    int pieces = 0;

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

        length += file.length();/*  ww w.j a  v  a  2s  . co  m*/

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

        try {
            while (channel.read(buffer) > 0) {
                if (buffer.remaining() == 0) {
                    buffer.clear();
                    results.add(executor.submit(new CallableChunkHasher(buffer)));
                }

                if (results.size() >= threads) {
                    pieces += accumulateHashes(hashes, results);
                }

                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.limit(buffer.position());
        buffer.position(0);
        results.add(executor.submit(new CallableChunkHasher(buffer)));
    }

    pieces += accumulateHashes(hashes, results);

    // Request orderly executor shutdown and wait for hashing tasks to
    // complete.
    executor.shutdown();
    while (!executor.isTerminated()) {
        Thread.sleep(10);
    }
    long elapsed = System.nanoTime() - start;

    int expectedPieces = (int) (Math.ceil((double) length / PIECE_LENGTH));
    logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.", new Object[] { files.size(),
            length, pieces, expectedPieces, String.format("%.1f", elapsed / 1e6), });

    return hashes.toString();
}

From source file:com.symbian.driver.plugins.romflash.Activator.java

public boolean FlashRom(String romLocation) {

    try {//from w w w .  j  ava 2s  .c om
        File rom = new File(romLocation);
        if (method.compareToIgnoreCase("serial") == 0) {
            if (!(switchOff() && switchOn())) {
                LOGGER.log(Level.SEVERE, "Could not reboot device, so No rom flashing.");
                return false;
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
            }
            File trgtTestFile = JarUtils.extractResource(Activator.class, "/resource/trgtest.exe");
            if (trgtTestFile.isFile()) {
                ProcessBuilder ld = new ProcessBuilder(trgtTestFile.getAbsolutePath(), portNumber,
                        rom.getCanonicalPath());
                ld.directory(trgtTestFile.getParentFile());
                Process pp = ld.start();
                LOGGER.log(Level.INFO, "started trgtest process");
                BufferedReader br = new BufferedReader(new InputStreamReader(pp.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                    LOGGER.log(Level.INFO, line);
                }
                //String answer = sb.toString();

                try {
                    LOGGER.log(Level.INFO, "going to wait now for trgtest to finish");
                    pp.waitFor();
                } catch (InterruptedException e) {
                    LOGGER.log(Level.SEVERE, "Failed to wait for trgtest.exe to finish.");
                }
                LOGGER.log(Level.INFO, "trgtest returned: " + pp.exitValue());
                pp.destroy();

            } else {
                LOGGER.log(Level.SEVERE, "Could not find trgtest.exe file.");
            }
        } else // usb rom loading
        {
            // switch the device off...
            switchOff();
            List<File> lis1 = Arrays.asList(File.listRoots());
            // get reboot plugin, and reboot the device
            switchOn(); // or just switch on as things may be
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
            }
            File[] listRoots2 = File.listRoots();
            // find the drive that made the difference!!
            File diff = null;
            for (File root : listRoots2) {
                if (!lis1.contains(root)) // found new drive
                {
                    diff = root;
                    break;
                }
            }
            File romfl = new File(diff, rom.getName());
            romfl.delete();
            File aCopyFrom = new File(rom.getCanonicalPath());
            FileChannel lSrcChannel = new FileInputStream(aCopyFrom).getChannel();
            FileChannel lDstChannel = new FileOutputStream(romfl).getChannel();
            lDstChannel.transferFrom(lSrcChannel, 0, lSrcChannel.size());
            lSrcChannel.close();
            lDstChannel.close();

            File syncFile = JarUtils.extractResource(Activator.class, "/resource/sync.exe");
            if (syncFile.isFile()) {

                ProcessBuilder ld = new ProcessBuilder(syncFile.getAbsolutePath(), "-r", "-e", diff.toString());

                ld.directory(syncFile.getParentFile());
                ld.start();
                // wait 10 seconds for the rom to load ...
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
                }
            } else {
                LOGGER.log(Level.SEVERE, "Could not find sync.exe file.");
            }
        }
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE, "Could not flash ROM " + lIOException.getMessage());
        return false;
    }
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
    }
    return true;
}

From source file:org.chimi.s4s.fileservice.FileLockBasedThumbnailCreator.java

@Override
public File create(FileData fileData, Size newSize) throws IOException {
    String thumbnailPath = getThumbnailPath(fileData.getFileId(), newSize);
    File thumbnailFile = new File(thumbnailPath);
    if (thumbnailFile.exists()) {
        // ? ?? /*www.  jav  a  2s.co m*/
        return thumbnailFile;
    }
    File lockFile = getLockFile(thumbnailPath);
    FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel();
    FileLock lock = null;
    try {
        lock = channel.tryLock();
    } catch (OverlappingFileLockException ex) {
    }

    if (lock == null) {
        // ??  , 1  ?? ?? ? ? 
        return createTemporaryThumbnail(thumbnailPath, fileData, newSize);
    }
    try {
        createThumbnail(thumbnailPath, fileData, newSize);
        return thumbnailFile;
    } finally {
        lock.release();
        channel.close();

        // TODO ? ?   
    }
}

From source file:eu.europa.esig.dss.DSSUtils.java

public static void copyFile(final String path, final File sourceFile, final File destinationFile)
        throws IOException {

    final File destinationPath = new File(path);
    if (!destinationPath.exists()) {
        destinationPath.mkdirs();/*from  w ww . jav a  2s .com*/
        destinationFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destinationFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:net.ytbolg.mcxa.ImportOldMc.java

void fileChannelCopy(File s, File t) {

    FileInputStream fi = null;/*from w  w  w. j a  v  a  2 s. com*/

    FileOutputStream fo = null;

    FileChannel in = null;

    FileChannel out = null;

    try {

        fi = new FileInputStream(s);

        fo = new FileOutputStream(t);

        in = fi.getChannel();//?

        out = fo.getChannel();//?

        in.transferTo(0, in.size(), out);//?in???out?

    } catch (IOException e) {

        e.printStackTrace();

    } finally {

        try {

            fi.close();

            in.close();

            fo.close();

            out.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

From source file:com.doplgangr.secrecy.FileSystem.File.java

public java.io.File readFile(CryptStateListener listener) {
    decrypting = true;//from   w w  w  . ja va 2 s. co m
    InputStream is = null;
    OutputStream out = null;
    java.io.File outputFile = null;
    try {
        outputFile = java.io.File.createTempFile("tmp" + name, "." + FileType, storage.getTempFolder());
        outputFile.mkdirs();
        outputFile.createNewFile();
        AES_Encryptor enc = new AES_Encryptor(key);
        is = new CipherInputStream(new FileInputStream(file), enc.decryptstream());
        listener.setMax((int) file.length());
        ReadableByteChannel inChannel = Channels.newChannel(is);
        FileChannel outChannel = new FileOutputStream(outputFile).getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(Config.bufferSize);
        while (inChannel.read(byteBuffer) >= 0 || byteBuffer.position() > 0) {
            byteBuffer.flip();
            outChannel.write(byteBuffer);
            byteBuffer.compact();
            listener.updateProgress((int) outChannel.size());
        }
        inChannel.close();
        outChannel.close();
        Util.log(outputFile.getName(), outputFile.length());
        return outputFile;
    } catch (FileNotFoundException e) {
        listener.onFailed(2);
        Util.log("Encrypted File is missing", e.getMessage());
    } catch (IOException e) {
        Util.log("IO Exception while decrypting", e.getMessage());
        if (e.getMessage().contains("pad block corrupted"))
            listener.onFailed(1);
        else
            e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        listener.Finished();
        decrypting = false;
        try {
            if (is != null) {
                is.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // An error occured. Too Bad
    if (outputFile != null)
        storage.purgeFile(outputFile);
    return null;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.FileUtil.java

public static boolean copyFile(final String sourceFilename, final String destFilename) {
    boolean success = false;
    FileChannel source = null;
    FileChannel destination = null;
    FileInputStream sourceStream = null;
    FileOutputStream destinationStream = null;
    final File destFile = new File(destFilename);
    final File sourceFile = new File(sourceFilename);
    try {/*from w  w w.  j  ava 2 s.  c  o m*/
        final long size = sourceFile.length();
        sourceStream = new FileInputStream(sourceFile);
        destinationStream = new FileOutputStream(destFile);
        source = sourceStream.getChannel();
        destination = destinationStream.getChannel();
        long toTransfer = size;
        while (toTransfer > 0) {
            toTransfer -= source.transferTo(size - toTransfer, toTransfer, destination);
        }
        success = true;
    } catch (IOException iox) {
        try {
            logger.error(
                    "Unable to copy " + sourceFile.getCanonicalPath() + " to " + destFile.getCanonicalPath(),
                    iox);
        } catch (IOException iox2) {
            logger.error("Unable to copy " + sourceFile.getName() + " OR get the canonical name", iox2);
        }
    } finally {
        try {
            if (source != null) {
                source.close();
                source = null;
            }
            if (destination != null) {
                destination.close();
                destination = null;
            }
            if (sourceStream != null) {
                sourceStream.close();
                sourceStream = null;
            }
            if (destinationStream != null) {
                destinationStream.close();
                destinationStream = null;
            }
        } catch (IOException iox3) {
            logger.error("Unable to close stream?!?", iox3);
        }
    }
    return success;
}

From source file:org.apache.cordova.backgroundDownload.BackgroundDownload.java

private void copyFile(File src, File dest) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dest).getChannel();
    try {//from ww  w . j  a  v a  2 s  .  com
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null) {
            inChannel.close();
        }
        if (outChannel != null) {
            outChannel.close();
        }
    }
}

From source file:com.kkbox.toolkit.image.KKImageRequest.java

private void moveFileTo(String originalPath, String targetPath) {
    fileLock.lock();/*from w ww .j  av a 2  s  .c o m*/
    File targetFile = new File(targetPath);
    targetFile.delete();
    FileChannel originalChannel = null;
    FileChannel targetChannel = null;
    try {
        originalChannel = new FileInputStream(originalPath).getChannel();
        targetChannel = new FileOutputStream(targetPath).getChannel();
        originalChannel.transferTo(0, originalChannel.size(), targetChannel);
    } catch (IOException e) {
    }
    try {
        if (originalChannel != null)
            originalChannel.close();
        if (targetChannel != null)
            targetChannel.close();
    } catch (IOException e) {
    }
    fileLock.unlock();
}