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.ros.internal.message.new_style.MessageLoader.java

private void addMessageDefinitionFromPaths(File searchPath, File messagePath, CharsetDecoder decoder)
        throws IOException {
    FileInputStream inputStream = new FileInputStream(messagePath);
    FileChannel channel = inputStream.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
    channel.read(buffer);//from  w w  w.j a v  a  2  s. com
    buffer.rewind();
    decoder.reset();
    String definition = decoder.decode(buffer).toString().trim();
    messageDefinitions.put(pathToMessageName(searchPath, messagePath), definition);
    channel.close();
    inputStream.close();
}

From source file:com.sqlite.multiread.java

public void run() {
    newSqLiteAdapter.openToRead();//ww w.  j av a 2  s.  c  o m
    long seconds1 = 0;
    long seconds2 = 0;
    Cursor cur = null;
    Transactions transactions = new Transactions();
    ArrayList<Long> array = new ArrayList<Long>();
    for (int i = 0; i < 10; i++) {
        seconds1 = System.currentTimeMillis();
        //cur = newSqLiteAdapter.queueAll("dammyTable", false, false, false,
        //         false, false, false, true, threadNum);
        seconds2 = System.currentTimeMillis();
        array.add(seconds2 - seconds1);
    }
    //   newSqLiteAdapter.close();
    FileOutputStream fos = null;
    try {
        byte[] data = new String("\nTotal time: " + transactions.average_time(array) / 8 + "ms  Thread Id: "
                + currentThread().getId() + " I Have read " + cur.getCount()).getBytes();

        File file = new File(Environment.getExternalStorageDirectory() + "/Aaa/", "threadsResults.txt");

        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

        FileLock lock = channel.lock();

        try {
            lock = channel.tryLock();
        } catch (OverlappingFileLockException e) {

        }

        fos = new FileOutputStream(file, true);
        fos.write(data);

        fos.flush();

        lock.release();
        channel.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.linagora.linshare.webservice.uploadrequest.impl.FlowUploaderRestServiceImpl.java

@Path("/")
@POST//from www  .  j  a  va  2s.  c  o m
@Consumes("multipart/form-data")
@Override
public Response uploadChunk(@Multipart(CHUNK_NUMBER) long chunkNumber,
        @Multipart(TOTAL_CHUNKS) long totalChunks, @Multipart(CHUNK_SIZE) long chunkSize,
        @Multipart(TOTAL_SIZE) long totalSize, @Multipart(IDENTIFIER) String identifier,
        @Multipart(FILENAME) String filename, @Multipart(RELATIVE_PATH) String relativePath,
        @Multipart(FILE) InputStream file, MultipartBody body,
        @Multipart(REQUEST_URL_UUID) String uploadRequestUrlUuid, @Multipart(PASSWORD) String password)
        throws BusinessException {

    logger.debug("upload chunk number : " + chunkNumber);
    identifier = cleanIdentifier(identifier);
    Validate.isTrue(isValid(chunkNumber, chunkSize, totalSize, identifier, filename));
    try {
        logger.debug("writing chunk number : " + chunkNumber);
        java.nio.file.Path tempFile = getTempFile(identifier);
        FileChannel fc = FileChannel.open(tempFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        byte[] byteArray = IOUtils.toByteArray(file);
        fc.write(ByteBuffer.wrap(byteArray), (chunkNumber - 1) * chunkSize);
        fc.close();
        chunkedFiles.get(identifier).addChunk(chunkNumber);
        if (isUploadFinished(identifier, chunkSize, totalSize)) {
            logger.debug("upload finished ");
            InputStream inputStream = Files.newInputStream(tempFile, StandardOpenOption.READ);
            File tempFile2 = getTempFile(inputStream, "rest-flowuploader", filename);
            try {
                uploadRequestUrlFacade.addUploadRequestEntry(uploadRequestUrlUuid, password, tempFile2,
                        filename);
            } finally {
                deleteTempFile(tempFile2);
            }
            ChunkedFile remove = chunkedFiles.remove(identifier);
            Files.deleteIfExists(remove.getPath());
            return Response.ok("upload success").build();
        } else {
            logger.debug("upload pending ");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Response.ok("upload success").build();
}

From source file:com.homesnap.webserver.AbstractRestApi.java

protected void copyFileUsingFileChannels(File source, File dest) throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {// ww  w  .  j  av a  2s .c o m
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}

From source file:com.bittorrent.mpetazzoni.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(Torrent.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() / Torrent.PIECE_LENGTH)) });

        length += file.length();/*from  w ww.  j av  a  2s.  c o 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 / Torrent.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.turn.ttorrent.common.Torrent.java

private static String hashFiles(List<File> files, int pieceLenght)
        throws InterruptedException, IOException, NoSuchAlgorithmException {
    int threads = getHashingThreadsCount();
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    ByteBuffer buffer = ByteBuffer.allocate(pieceLenght);
    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() / pieceLenght)) });

        length += file.length();//from   w w  w.j  a v  a 2  s  . c  om

        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 / pieceLenght));
    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:voldemort.store.cachestore.impl.ChannelStore.java

private void close(FileChannel channel) {
    try {/* w  w w  . ja  v  a2s. co m*/
        if (channel != null)
            channel.close();
    } catch (IOException ex) {
        logger.error(ex.getMessage(), ex);
        // swallow exception
    }
}

From source file:edu.harvard.iq.dvn.core.analysis.NetworkDataServiceBean.java

private void copyFile(StudyFileEditBean editBean) throws IOException {
    File tempFile = new File(editBean.getTempSystemFileLocation());
    dbgLog.fine("begin copyFile()");
    // create a sub-directory "ingested"
    File newDir = new File(tempFile.getParentFile(), "ingested");

    if (!newDir.exists()) {
        newDir.mkdirs();/*from w  w  w .  ja  v  a2  s.  com*/
    }
    dbgLog.fine("newDir: abs path:\n" + newDir.getAbsolutePath());

    File newFile = new File(newDir, tempFile.getName());

    FileInputStream fis = new FileInputStream(tempFile);
    FileOutputStream fos = new FileOutputStream(newFile);
    FileChannel fcin = fis.getChannel();
    FileChannel fcout = fos.getChannel();
    fcin.transferTo(0, fcin.size(), fcout);
    fcin.close();
    fcout.close();
    fis.close();
    fos.close();

    dbgLog.fine("newFile: abs path:\n" + newFile.getAbsolutePath());

    // store the tab-file location
    editBean.setIngestedSystemFileLocation(newFile.getAbsolutePath());

}

From source file:org.forgerock.openidm.script.javascript.JavaScriptFactory.java

private Script initializeScript(String name, String source, boolean sharedScope) throws ScriptException {
    initDebugListener();//from  www. j a  v a2 s  .c o  m
    if (debugInitialised) {
        try {
            FileChannel outChannel = new FileOutputStream(getTargetFile(name)).getChannel();
            FileLock outLock = outChannel.lock();
            ByteBuffer buf = ByteBuffer.allocate(source.length());
            buf.put(source.getBytes("UTF-8"));
            buf.flip();
            outChannel.write(buf);
            outLock.release();
            outChannel.close();
        } catch (IOException e) {
            logger.warn("JavaScript source was not updated for {}", name, e);
        }
    }
    return new JavaScript(name, source, sharedScope);
}

From source file:org.chromium.APKPackager.java

private void copyFile(File src, File dest) throws FileNotFoundException, IOException {
    FileInputStream istream = new FileInputStream(src);
    FileOutputStream ostream = new FileOutputStream(dest);
    FileChannel input = istream.getChannel();
    FileChannel output = ostream.getChannel();

    try {/* ww w  .ja  v a  2s .  co  m*/
        input.transferTo(0, input.size(), output);
    } finally {
        istream.close();
        ostream.close();
        input.close();
        output.close();
    }
}