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.apache.tez.runtime.library.common.shuffle.Fetcher.java

private FileLock getLock() throws OverlappingFileLockException, InterruptedException, IOException {
    File lockFile = localFs.pathToFile(new Path(lockPath, host + ".lock"));

    final boolean created = lockFile.createNewFile();

    if (created == false && !lockFile.exists()) {
        // bail-out cleanly
        return null;
    }//from w w  w . ja v a2 s.  c o  m

    // invariant - file created (winner writes to this file)
    // caveat: closing lockChannel does close the file (do not double close)
    // JDK7 - TODO: use AsynchronousFileChannel instead of RandomAccessFile
    FileChannel lockChannel = new RandomAccessFile(lockFile, "rws").getChannel();
    FileLock xlock = null;

    xlock = lockChannel.tryLock(0, Long.MAX_VALUE, false);
    if (xlock != null) {
        return xlock;
    }
    lockChannel.close();
    return null;
}

From source file:edu.harvard.iq.dataverse.dataaccess.DataFileIO.java

public void copyPath(Path fileSystemPath) throws IOException {
    long newFileSize = -1;
    // if this is a local fileystem file, we'll use a 
    // quick Files.copy method: 
    if (isLocalFile()) {
        Path outputPath = null;/*from  w  w  w.j a v a2s. c o  m*/
        try {
            outputPath = getFileSystemPath();
        } catch (IOException ex) {
            outputPath = null;
        }
        if (outputPath != null) {
            Files.copy(fileSystemPath, outputPath, StandardCopyOption.REPLACE_EXISTING);
            newFileSize = outputPath.toFile().length();
        }

    } else {
        // otherwise we'll open a writable byte channel and 
        // copy the source file bytes using Channel.transferTo():

        WritableByteChannel writeChannel = null;
        FileChannel readChannel = null;
        String failureMsg = null;

        try {

            open(DataAccessOption.WRITE_ACCESS);
            writeChannel = getWriteChannel();
            readChannel = new FileInputStream(fileSystemPath.toFile()).getChannel();

            long bytesPerIteration = 16 * 1024; // 16K bytes
            long start = 0;
            while (start < readChannel.size()) {
                readChannel.transferTo(start, bytesPerIteration, writeChannel);
                start += bytesPerIteration;
            }
            newFileSize = readChannel.size();

        } catch (IOException ioex) {
            failureMsg = ioex.getMessage();
            if (failureMsg == null) {
                failureMsg = "Unknown exception occured.";
            }
        } finally {
            if (readChannel != null) {
                try {
                    readChannel.close();
                } catch (IOException e) {
                }
            }
            if (writeChannel != null) {
                try {
                    writeChannel.close();
                } catch (IOException e) {
                }
            }
        }

        if (failureMsg != null) {
            throw new IOException(failureMsg);
        }
    }

    // if it has worked successfully, we also need to reset the size
    // of the object. 
    setSize(newFileSize);
}

From source file:li.barter.utils.Utils.java

public static boolean copyFile(final File src, final File dst) {
    boolean returnValue = true;

    FileChannel inChannel = null, outChannel = null;

    try {/* w  w  w  . j av a 2 s.c  om*/

        inChannel = new FileInputStream(src).getChannel();
        outChannel = new FileOutputStream(dst).getChannel();

    } catch (final FileNotFoundException fnfe) {

        Logger.d(TAG, "inChannel/outChannel FileNotFoundException");
        fnfe.printStackTrace();
        return false;
    }

    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);

    } catch (final IllegalArgumentException iae) {

        Logger.d(TAG, "TransferTo IllegalArgumentException");
        iae.printStackTrace();
        returnValue = false;

    } catch (final NonReadableChannelException nrce) {

        Logger.d(TAG, "TransferTo NonReadableChannelException");
        nrce.printStackTrace();
        returnValue = false;

    } catch (final NonWritableChannelException nwce) {

        Logger.d(TAG, "TransferTo NonWritableChannelException");
        nwce.printStackTrace();
        returnValue = false;

    } catch (final ClosedByInterruptException cie) {

        Logger.d(TAG, "TransferTo ClosedByInterruptException");
        cie.printStackTrace();
        returnValue = false;

    } catch (final AsynchronousCloseException ace) {

        Logger.d(TAG, "TransferTo AsynchronousCloseException");
        ace.printStackTrace();
        returnValue = false;

    } catch (final ClosedChannelException cce) {

        Logger.d(TAG, "TransferTo ClosedChannelException");
        cce.printStackTrace();
        returnValue = false;

    } catch (final IOException ioe) {

        Logger.d(TAG, "TransferTo IOException");
        ioe.printStackTrace();
        returnValue = false;

    } finally {

        if (inChannel != null) {
            try {

                inChannel.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }

        if (outChannel != null) {
            try {
                outChannel.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }

    }

    return returnValue;
}

From source file:org.alfresco.repo.content.AbstractWritableContentStoreTest.java

/**
 * Tests random access writing//from w  ww.jav a2  s.c o  m
 * <p>
 * Only executes if the writer implements {@link RandomAccessContent}.
 */
@Test
public void testRandomAccessWrite() throws Exception {
    ContentWriter writer = getWriter();

    FileChannel fileChannel = writer.getFileChannel(true);
    assertNotNull("No channel given", fileChannel);

    // check that no other content access is allowed
    try {
        writer.getWritableChannel();
        fail("Second channel access allowed");
    } catch (RuntimeException e) {
        // expected
    }

    // write some content in a random fashion (reverse order)
    byte[] content = new byte[] { 1, 2, 3 };
    for (int i = content.length - 1; i >= 0; i--) {
        ByteBuffer buffer = ByteBuffer.wrap(content, i, 1);
        fileChannel.write(buffer, i);
    }

    // close the channel
    fileChannel.close();
    assertTrue("Writer not closed", writer.isClosed());

    // check the content
    ContentReader reader = writer.getReader();
    ReadableByteChannel channelReader = reader.getReadableChannel();
    ByteBuffer buffer = ByteBuffer.allocateDirect(3);
    int count = channelReader.read(buffer);
    assertEquals("Incorrect number of bytes read", 3, count);
    for (int i = 0; i < content.length; i++) {
        assertEquals("Content doesn't match", content[i], buffer.get(i));
    }

    // get a new writer from the store, using the existing content and perform a truncation check
    ContentContext writerTruncateCtx = new ContentContext(writer.getReader(), null);
    ContentWriter writerTruncate = getStore().getWriter(writerTruncateCtx);
    assertEquals("Content size incorrect", 0, writerTruncate.getSize());
    // get the channel with truncation
    FileChannel fcTruncate = writerTruncate.getFileChannel(true);
    fcTruncate.close();
    assertEquals("Content not truncated", 0, writerTruncate.getSize());

    // get a new writer from the store, using the existing content and perform a non-truncation check
    ContentContext writerNoTruncateCtx = new ContentContext(writer.getReader(), null);
    ContentWriter writerNoTruncate = getStore().getWriter(writerNoTruncateCtx);
    assertEquals("Content size incorrect", 0, writerNoTruncate.getSize());
    // get the channel without truncation
    FileChannel fcNoTruncate = writerNoTruncate.getFileChannel(false);
    fcNoTruncate.close();
    assertEquals("Content was truncated", writer.getSize(), writerNoTruncate.getSize());
}

From source file:org.apache.htrace.impl.HTracedSpanReceiver.java

void appendToDroppedSpansLog(String text) throws IOException {
    // Is the dropped spans log is disabled?
    if (conf.droppedSpansLogPath.isEmpty() || (conf.droppedSpansLogMaxSize == 0)) {
        return;/*from  w  w w.j  a v  a  2  s .c  o  m*/
    }
    FileLock lock = null;
    String msg = ISO_DATE_FORMAT.format(new Date()) + ": " + text;
    ByteBuffer bb = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
    // FileChannel locking corresponds to advisory locking on UNIX.  It will
    // protect multiple processes from attempting to write to the same dropped
    // spans log at once.  However, within a single process, we need this
    // synchronized block to ensure that multiple HTracedSpanReceiver objects
    // don't try to write to the same log at once.  (It is unusal to configure
    // multiple HTracedSpanReceiver objects, but possible.)
    synchronized (HTracedSpanReceiver.class) {
        FileChannel channel = FileChannel.open(Paths.get(conf.droppedSpansLogPath), APPEND, CREATE, WRITE);
        try {
            lock = channel.lock();
            long size = channel.size();
            if (size > conf.droppedSpansLogMaxSize) {
                throw new IOException("Dropped spans log " + conf.droppedSpansLogPath + " is already " + size
                        + " bytes; will not add to it.");
            } else if ((size == 0) && (DROPPED_SPANS_FILE_PERMS != null)) {
                // Set the permissions of the dropped spans file so that other
                // processes can write to it.
                Files.setPosixFilePermissions(Paths.get(conf.droppedSpansLogPath), DROPPED_SPANS_FILE_PERMS);
            }
            channel.write(bb);
        } finally {
            try {
                if (lock != null) {
                    lock.release();
                }
            } finally {
                channel.close();
            }
        }
    }
}

From source file:org.cytobank.fcs_files.events.MemoryEvents.java

protected synchronized boolean writeOut() {
    if (memoryEventsArray == null)
        return false;

    File memoryEventsArrayOnDisk = null;

    synchronized (memoryEventsArray) {
        memoryEventsArrayOnDisk = memoryEventsArray.getOnDisk();

        if (memoryEventsArrayOnDisk != null || events == null)
            return false;

        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;

        try {//from  w w  w . ja  v a2 s .  c o m
            memoryEventsArrayOnDisk = File.createTempFile("memoryEventsArrayOnDisk", "evt");
            memoryEventsArrayOnDisk.deleteOnExit();
            randomAccessFile = new RandomAccessFile(memoryEventsArrayOnDisk, "rw");
            fileChannel = randomAccessFile.getChannel();

            MappedByteBuffer mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0,
                    numberOfEvents * BYTES_PER_DOUBLE);
            DoubleBuffer doubleBuffer = mappedByteBuffer.asDoubleBuffer();
            doubleBuffer.put(events, 0, numberOfEvents);
            mappedByteBuffer.force();
            fileChannel.close();
            randomAccessFile.close();

            memoryEventsArray.setOnDisk(memoryEventsArrayOnDisk);

        } catch (IOException ioe) {
            logger.log(Level.INFO, "::::: Failed to write out MemoryEventsArray :::::", ioe);
            if (memoryEventsArrayOnDisk != null) {
                memoryEventsArrayOnDisk.delete();
                memoryEventsArrayOnDisk = null;
            }
        } finally {
            memoryEventsArrayOnDisk.delete();
        }
    }

    return true;

}

From source file:org.apache.nifi.processors.standard.TailFile.java

private void cleanReader(TailFileObject tfo) {
    if (tfo.getState() == null) {
        return;/* ww w  .  j av a 2  s .  com*/
    }

    final FileChannel reader = tfo.getState().getReader();
    if (reader == null) {
        return;
    }

    try {
        reader.close();
        getLogger().debug("Closed FileChannel {}", new Object[] { reader });
    } catch (final IOException ioe) {
        getLogger().warn("Failed to close file handle during cleanup");
    }
}

From source file:org.alfresco.repo.content.AbstractWritableContentStoreTest.java

/**
 * Tests random access reading//from   ww w. j a v  a  2 s  .  co  m
 * <p>
 * Only executes if the reader implements {@link RandomAccessContent}.
 */
@Test
public void testRandomAccessRead() throws Exception {
    ContentWriter writer = getWriter();
    // put some content
    String content = "ABC";
    byte[] bytes = content.getBytes();
    writer.putContent(content);
    ContentReader reader = writer.getReader();

    FileChannel fileChannel = reader.getFileChannel();
    assertNotNull("No channel given", fileChannel);

    // check that no other content access is allowed
    try {
        reader.getReadableChannel();
        fail("Second channel access allowed");
    } catch (RuntimeException e) {
        // expected
    }

    // read the content
    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    int count = fileChannel.read(buffer);
    assertEquals("Incorrect number of bytes read", bytes.length, count);
    // transfer back to array
    buffer.rewind();
    buffer.get(bytes);
    String checkContent = new String(bytes);
    assertEquals("Content read failure", content, checkContent);
    fileChannel.close();
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.TestContainerManager.java

private ByteBuffer readFileToByteBuffer(File source) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(128);
    FileChannel fileChannel = new FileInputStream(source).getChannel();
    fileChannel.read(buffer);/*from www .j  a  v  a 2  s .c  o m*/
    fileChannel.close();
    buffer.flip();
    return buffer;
}

From source file:com.colorchen.qbase.utils.FileUtil.java

/**
 * ?/*from  w  w w .  ja v a  2 s. com*/
 *
 * @param outFile
 * @param files
 */
public static void mergeFiles(Context context, File outFile, List<File> files) {
    FileChannel outChannel = null;
    try {
        outChannel = new FileOutputStream(outFile).getChannel();
        for (File f : files) {
            FileChannel fc = new FileInputStream(f).getChannel();
            ByteBuffer bb = ByteBuffer.allocate(BUFSIZE);
            while (fc.read(bb) != -1) {
                bb.flip();
                outChannel.write(bb);
                bb.clear();
            }
            fc.close();
        }
        Log.d(TAG, "?");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {
            if (outChannel != null) {
                outChannel.close();
            }
        } catch (IOException ignore) {
        }
    }
}