Example usage for java.io RandomAccessFile getChannel

List of usage examples for java.io RandomAccessFile getChannel

Introduction

In this page you can find the example usage for java.io RandomAccessFile getChannel.

Prototype

public final FileChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.FileChannel FileChannel object associated with this file.

Usage

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void testNIO() throws Exception {
    byte[] INITIAL = new byte[] { 1, 2, 3, 4 };
    byte[] EXTRA = new byte[] { 5, 6, 7, 8 };
    byte[] FULL = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] FIFTH = new byte[] { 87 };
    byte[] FULL_WITH_FIFTH = new byte[] { 1, 2, 3, 4, 87, 6, 7, 8 };

    // Create temp-file with content
    File temp = createTempFile();
    FileOutputStream fileOut = new FileOutputStream(temp, true);
    fileOut.write(INITIAL);//from w  ww .j  a  va  2 s  .c o m
    fileOut.close();

    checkContent("The plain test-file should be correct", temp, INITIAL);
    {
        // Read the 4 bytes
        RandomAccessFile input = new RandomAccessFile(temp, "r");
        FileChannel channelIn = input.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(4096);
        channelIn.position(0);
        assertEquals("Buffer read should read full length", INITIAL.length, channelIn.read(buffer));
        buffer.position(0);

        checkContent("Using buffer should produce the right bytes", INITIAL, buffer);
        channelIn.close();
        input.close();
    }
    {
        // Fill new buffer
        ByteBuffer outBuffer = ByteBuffer.allocate(4096);
        outBuffer.put(EXTRA);
        outBuffer.flip();
        assertEquals("The limit of the outBuffer should be correct", EXTRA.length, outBuffer.limit());

        // Append new buffer to end
        RandomAccessFile output = new RandomAccessFile(temp, "rw");
        FileChannel channelOut = output.getChannel();
        channelOut.position(INITIAL.length);
        assertEquals("All bytes should be written", EXTRA.length, channelOut.write(outBuffer));
        channelOut.close();
        output.close();
        checkContent("The resulting file should have the full output", temp, FULL);
    }

    {
        // Fill single byte buffer
        ByteBuffer outBuffer2 = ByteBuffer.allocate(4096);
        outBuffer2.put(FIFTH);
        outBuffer2.flip();
        assertEquals("The limit of the second outBuffer should be correct", FIFTH.length, outBuffer2.limit());

        // Insert byte in the middle
        RandomAccessFile output2 = new RandomAccessFile(temp, "rw");
        FileChannel channelOut2 = output2.getChannel();
        channelOut2.position(4);
        assertEquals("The FIFTH should be written", FIFTH.length, channelOut2.write(outBuffer2));
        channelOut2.close();
        output2.close();
        checkContent("The resulting file with fifth should be complete", temp, FULL_WITH_FIFTH);
    }
}

From source file:net.timewalker.ffmq4.storage.data.impl.journal.BlockBasedDataStoreJournal.java

private void syncStoreFile(RandomAccessFile storeFile) throws JournalException {
    try {//w w  w. j  a v a  2s. c  o m
        switch (storageSyncMethod) {
        case StorageSyncMethod.FD_SYNC:
            storeFile.getFD().sync();
            break;
        case StorageSyncMethod.CHANNEL_FORCE_NO_META:
            storeFile.getChannel().force(false);
            break;
        default:
            throw new JournalException("Unsupported sync method : " + storageSyncMethod);
        }
    } catch (IOException e) {
        log.error("[" + baseName + "] Could not sync store file", e);
        throw new JournalException("Could not sync store file");
    }
}

From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java

/**
 * Obtains a file lock on the repository lock file.
 *///from  w  w  w  .j a v  a 2 s . c om
protected RepositoryFileLock obtainRepositoryFileLock(final boolean shared, final int timeout)
        throws IOException {
    Log logger = this.getLog();

    if (logger.isDebugEnabled())
        logger.debug("Obtaining repository file lock (shared: " + shared + ").");

    RepositoryFileLock repositoryFileLock = null;
    FileLock lock = null;
    final long beginWait = System.currentTimeMillis();

    while (repositoryFileLock == null) {
        try {
            RandomAccessFile lockFile = new RandomAccessFile(
                    new File(moduleRepositoryDirectory, LOCK_FILE_NAME), "rws");
            FileChannel channel = lockFile.getChannel();

            // Attempt to obtain a lock on the file
            lock = channel.tryLock(0L, Long.MAX_VALUE, shared);
            if (!shared && (lockFile.length() == 0)) {
                lockFile.write(new String("LOCK").getBytes());
                lockFile.getFD().sync();
            }
            repositoryFileLock = new RepositoryFileLock(lockFile, lock);
        } catch (IOException ioe) {
            if (logger.isDebugEnabled())
                logger.debug("Error obtaining repository file lock (shared: " + shared + ").", ioe);
            if (timeout < 0)
                throw ioe;
        } catch (OverlappingFileLockException ofle) {
            if (logger.isDebugEnabled())
                logger.debug("Error obtaining repository file lock (shared: " + shared + ").", ofle);
            if (timeout < 0)
                throw ofle;
        }

        if (repositoryFileLock == null) // This statement shouldn't be reaced if timeout is < 0
        {
            if ((System.currentTimeMillis() - beginWait) > timeout) // Wait a maximum of timeout milliseconds on lock
            {
                throw new IOException("Timeout while waiting for file lock on repository lock file!");
            } else {
                // Otherwise - wait a while before trying to obtain a lock again
                try {
                    Thread.sleep(Math.min(250, timeout - (System.currentTimeMillis() - beginWait)));
                } catch (InterruptedException ie) {
                }
            }
        }
    }

    if (logger.isDebugEnabled())
        logger.debug("Repository file lock (shared: " + shared + ") obtained.");

    return repositoryFileLock;
}

From source file:com.linkedin.helix.store.file.FilePropertyStore.java

@Override
public void updatePropertyUntilSucceed(String key, DataUpdater<T> updater, boolean createIfAbsent) {
    String path = getPath(key);/*  ww  w.  j ava 2 s.  co m*/
    File file = new File(path);
    RandomAccessFile raFile = null;
    FileLock fLock = null;

    try {
        _readWriteLock.writeLock().lock();
        if (!file.exists()) {
            FileUtils.touch(file);
        }

        raFile = new RandomAccessFile(file, "rw");
        FileChannel fChannel = raFile.getChannel();
        fLock = fChannel.lock();

        T current = getProperty(key);
        T update = updater.update(current);
        setProperty(key, update);
    } catch (Exception e) {
        logger.error("fail to updatePropertyUntilSucceed, path:" + path, e);
    } finally {
        _readWriteLock.writeLock().unlock();
        try {
            if (fLock != null && fLock.isValid()) {
                fLock.release();
            }

            if (raFile != null) {
                raFile.close();
            }
        } catch (IOException e) {
            logger.error("fail to close file, path:" + path, e);
        }
    }
}

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  ww  . j  a v a 2 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:com.pheromone.plugins.FileUtils.java

/**
 * Truncate the file to size/*www.  ja v  a2  s  .  c  o m*/
 *
 * @param filename
 * @param size
 * @throws FileNotFoundException, IOException
 */
private long truncateFile(String filename, long size) throws FileNotFoundException, IOException {
    RandomAccessFile raf = new RandomAccessFile(filename, "rw");

    if (raf.length() >= size) {
        FileChannel channel = raf.getChannel();
        channel.truncate(size);
        return size;
    }

    return raf.length();
}

From source file:com.MustacheMonitor.MustacheMonitor.FileUtils.java

/**
 * Truncate the file to size//  w w w  . j  a  v  a2s.com
 *
 * @param filename
 * @param size
 * @throws FileNotFoundException, IOException
 */
private long truncateFile(String filename, long size) throws FileNotFoundException, IOException {
    filename = stripFileProtocol(filename);

    RandomAccessFile raf = new RandomAccessFile(filename, "rw");

    if (raf.length() >= size) {
        FileChannel channel = raf.getChannel();
        channel.truncate(size);
        return size;
    }

    return raf.length();
}

From source file:org.ros.osgi.deployment.master.internal.NettyWebServerHandler.java

/**
 * Attempt to handle an HTTP request by scanning through all registered
 * handlers.//w w  w  .  j  av a  2 s .co  m
 *
 * @param ctx
 *          The context for the request.
 * @param req
 *          The request.
 * @return True if the request was handled, false otherwise.
 */
private boolean handleWebRequest(ChannelHandlerContext ctx, HttpRequest req) throws IOException {
    String url = req.getUri();
    int pos = url.indexOf('?');
    if (pos != -1)
        url = url.substring(0, pos);

    int luriPrefixLength = uriPrefix.length();
    String bundleName = url.substring(url.indexOf(uriPrefix) + luriPrefixLength);

    File file = featureRepository.getFeatureFile(bundleName);
    if (file == null) {
        return false;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        // sendError(ctx, NOT_FOUND);

        return false;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);

    Channel ch = ctx.getChannel();

    // Write the initial line and the header.
    ch.write(response);

    // Write the content.
    ChannelFuture writeFuture;
    if (ch.getPipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = ch.write(region);
        writeFuture.addListener(new ChannelFutureProgressListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                region.releaseExternalResources();
            }

            @Override
            public void operationProgressed(ChannelFuture arg0, long arg1, long arg2, long arg3)
                    throws Exception {
                // Do nothing
            }

        });
    }

    // Decide whether to close the connection or not.
    if (!isKeepAlive(req)) {
        // Close the connection when the whole content is written out.
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }

    return true;
}

From source file:org.cloudata.core.commitlog.CommitLogServer.java

public String rollback(String dirName, String position) {
    LOG.debug("rollback is called! with dirName : " + dirName);
    RandomAccessFile file = null;
    try {/*from  w  w  w .j  av a  2  s  . c o  m*/
        File logFile = new File(commitLogStoreFile,
                CommitLogFileChannel.getLogFileName(dirName, Constants.PIPE_CL_FILE_NAME + listener.port));

        file = new RandomAccessFile(logFile, "rws");
        file.getChannel().truncate(Long.parseLong(position));
    } catch (IOException e) {
        LOG.warn("rollbacking file is fail dir [" + dirName + "], pos : " + position, e);
        return "ABORT";
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
            }
        }
    }

    return "OK";
}

From source file:com.wondersgroup.cloud.deployment.file.FileServerHandler.java

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) e.getMessage();
    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;//from   w  w w  .  ja v a2s.  c o m
    }

    String srcPath = request.getHeader("srcPath");
    String ipList = request.getHeader("ipList");
    // ??app test: D:\cloud-deploy\DSC01575.JPG
    final String path = srcPath;// sanitizeUri(request.getUri()); "D:\\cloud-deploy\\AppTest.war";// 
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);

    response.setHeader("Content-disposition", "attachment;filename=" + file.getName());

    Channel ch = e.getChannel();

    // Write the initial line and the header.
    ch.write(response);

    // Write the content.
    ChannelFuture writeFuture;
    if (ch.getPipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = ch.write(region);
        writeFuture.addListener(new ChannelFutureProgressListener() {
            public void operationComplete(ChannelFuture future) {
                region.releaseExternalResources();
            }

            public void operationProgressed(ChannelFuture future, long amount, long current, long total) {
                System.out.printf("%s: %d / %d (+%d)%n", path, current, total, amount);
            }
        });
    }

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }
}