Example usage for java.io RandomAccessFile close

List of usage examples for java.io RandomAccessFile close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this random access file stream and releases any system resources associated with the stream.

Usage

From source file:com.devilyang.musicstation.cache.ACache.java

/**
 * ? byte ?/*from   w  ww . j  a va  2s  .c  o m*/
 * 
 * @param key
 * @return byte ?
 */
public byte[] getAsBinary(String key) {
    RandomAccessFile RAFile = null;
    boolean removeFile = false;
    try {
        File file = mCacheManager.get(key);
        if (!file.exists())
            return null;
        RAFile = new RandomAccessFile(file, "r");
        byte[] byteArray = new byte[(int) RAFile.length()];
        RAFile.read(byteArray);
        if (!Utils.isDue(byteArray)) {
            return Utils.clearDateInfo(byteArray);
        } else {
            removeFile = true;
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (RAFile != null) {
            try {
                RAFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (removeFile)
            remove(key);
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.NNStorage.java

@Override
protected void corruptPreUpgradeStorage(File rootDir) throws IOException {
    File oldImageDir = new File(rootDir, "image");
    if (!oldImageDir.exists())
        if (!oldImageDir.mkdir())
            throw new IOException("Cannot create directory " + oldImageDir);
    File oldImage = new File(oldImageDir, "fsimage");
    if (!oldImage.exists())
        // recreate old image file to let pre-upgrade versions fail
        if (!oldImage.createNewFile())
            throw new IOException("Cannot create file " + oldImage);
    RandomAccessFile oldFile = new RandomAccessFile(oldImage, "rws");
    // write new version into old image file
    try {//w  w w. ja  v a2s  .c  o  m
        writeCorruptedData(oldFile);
    } finally {
        oldFile.close();
    }
}

From source file:com.asakusafw.runtime.util.lock.LocalFileLockProvider.java

@Override
public LocalFileLockObject<T> tryLock(T target) throws IOException {
    if (baseDirectory.mkdirs() == false && baseDirectory.isDirectory() == false) {
        throw new IOException(MessageFormat.format("Failed to create lock directory: {0}", baseDirectory));
    }//from ww w  .j  av  a 2 s .  co  m
    String fileName = String.format("%08x.lck", target == null ? -1 : target.hashCode()); //$NON-NLS-1$
    File lockFile = new File(baseDirectory, fileName);
    RandomAccessFile fd = new RandomAccessFile(lockFile, "rw"); //$NON-NLS-1$
    boolean success = false;
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug(MessageFormat.format("Start to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$
                    target, lockFile));
        }
        FileLock lockEntity = getLock(target, lockFile, fd);
        if (lockEntity == null) {
            return null;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Finished to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$
                        target, lockFile));
            }
            try {
                fd.seek(0L);
                fd.setLength(0L);
                fd.write(String.valueOf(target).getBytes(ENCODING));
                success = true;
                return new LocalFileLockObject<>(target, lockFile, fd, lockEntity);
            } finally {
                if (success == false) {
                    lockEntity.release();
                }
            }
        }
    } finally {
        if (success == false) {
            fd.close();
        }
    }
}

From source file:org.apache.flume.channel.file.Log.java

/**
 * Attempts to acquire an exclusive lock on the directory.
 *
 * @return A lock object representing the newly-acquired lock or
 * <code>null</code> if directory is already locked.
 * @throws IOException if locking fails.
 *//*from  www  .j a v  a2s.c  o  m*/
@SuppressWarnings("resource")
private FileLock tryLock(File dir) throws IOException {
    File lockF = new File(dir, FILE_LOCK);
    lockF.deleteOnExit();
    RandomAccessFile file = new RandomAccessFile(lockF, "rws");
    FileLock res = null;
    try {
        res = file.getChannel().tryLock();
    } catch (OverlappingFileLockException oe) {
        file.close();
        return null;
    } catch (IOException e) {
        LOGGER.error("Cannot create lock on " + lockF, e);
        file.close();
        throw e;
    }
    return res;
}

From source file:org.myframe.http.FileRequest.java

public byte[] handleResponse(HttpResponse response) throws IOException, KJHttpException {
    HttpEntity entity = response.getEntity();
    long fileSize = entity.getContentLength();
    if (fileSize <= 0) {
        MLoger.debug("Response doesn't present Content-Length!");
    }//from   w  ww . j a  v  a 2  s  . co m

    long downloadedSize = mTemporaryFile.length();
    boolean isSupportRange = HttpUtils.isSupportRange(response);
    if (isSupportRange) {
        fileSize += downloadedSize;

        String realRangeValue = HttpUtils.getHeader(response, "Content-Range");
        if (!TextUtils.isEmpty(realRangeValue)) {
            String assumeRangeValue = "bytes " + downloadedSize + "-" + (fileSize - 1);
            if (TextUtils.indexOf(realRangeValue, assumeRangeValue) == -1) {
                throw new IllegalStateException("The Content-Range Header is invalid Assume[" + assumeRangeValue
                        + "] vs Real[" + realRangeValue + "], " + "please remove the temporary file ["
                        + mTemporaryFile + "].");
            }
        }
    }

    if (fileSize > 0 && mStoreFile.length() == fileSize) {
        mStoreFile.renameTo(mTemporaryFile);
        mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, fileSize);
        return null;
    }

    RandomAccessFile tmpFileRaf = new RandomAccessFile(mTemporaryFile, "rw");
    if (isSupportRange) {
        tmpFileRaf.seek(downloadedSize);
    } else {
        tmpFileRaf.setLength(0);
        downloadedSize = 0;
    }

    try {
        InputStream in = entity.getContent();
        if (HttpUtils.isGzipContent(response) && !(in instanceof GZIPInputStream)) {
            in = new GZIPInputStream(in);
        }
        byte[] buffer = new byte[6 * 1024]; // 6K buffer
        int offset;

        while ((offset = in.read(buffer)) != -1) {
            tmpFileRaf.write(buffer, 0, offset);

            downloadedSize += offset;
            mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, downloadedSize);

            if (isCanceled()) {
                break;
            }
        }
    } finally {
        try {
            if (entity != null)
                entity.consumeContent();
        } catch (Exception e) {
            MLoger.debug("Error occured when calling consumingContent");
        }
        tmpFileRaf.close();
    }
    return null;
}

From source file:com.scut.easyfe.network.kjFrame.http.FileRequest.java

public byte[] handleResponse(HttpResponse response) throws IOException, KJHttpException {
    HttpEntity entity = response.getEntity();
    long fileSize = entity.getContentLength();
    if (fileSize <= 0) {
        KJLoger.debug("Response doesn't present Content-Length!");
    }/*from   w w  w .  j  ava 2 s .c  o m*/

    long downloadedSize = mTemporaryFile.length();
    boolean isSupportRange = HttpUtils.isSupportRange(response);
    if (isSupportRange) {
        fileSize += downloadedSize;

        String realRangeValue = HttpUtils.getHeader(response, "Content-Range");
        if (!TextUtils.isEmpty(realRangeValue)) {
            String assumeRangeValue = "bytes " + downloadedSize + "-" + (fileSize - 1);
            if (TextUtils.indexOf(realRangeValue, assumeRangeValue) == -1) {
                throw new IllegalStateException("The Content-Range Header is invalid Assume[" + assumeRangeValue
                        + "] vs Real[" + realRangeValue + "], " + "please remove the temporary file ["
                        + mTemporaryFile + "].");
            }
        }
    }

    if (fileSize > 0 && mStoreFile.length() == fileSize) {
        mStoreFile.renameTo(mTemporaryFile);
        mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, fileSize);
        return null;
    }

    RandomAccessFile tmpFileRaf = new RandomAccessFile(mTemporaryFile, "rw");
    if (isSupportRange) {
        tmpFileRaf.seek(downloadedSize);
    } else {
        tmpFileRaf.setLength(0);
        downloadedSize = 0;
    }

    try {
        InputStream in = entity.getContent();
        if (HttpUtils.isGzipContent(response) && !(in instanceof GZIPInputStream)) {
            in = new GZIPInputStream(in);
        }
        byte[] buffer = new byte[6 * 1024]; // 6K buffer
        int offset;

        while ((offset = in.read(buffer)) != -1) {
            tmpFileRaf.write(buffer, 0, offset);

            downloadedSize += offset;
            mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, downloadedSize);

            if (isCanceled()) {
                break;
            }
        }
    } finally {
        try {
            if (entity != null)
                entity.consumeContent();
        } catch (Exception e) {
            KJLoger.debug("Error occured when calling consumingContent");
        }
        tmpFileRaf.close();
    }
    return null;
}

From source file:org.apache.cordova.core.FileUtils.java

/**
 * Truncate the file to size/*from   w w  w  .  j a v a 2s .  c  o  m*/
 *
 * @param filename
 * @param size
 * @throws FileNotFoundException, IOException
 * @throws NoModificationAllowedException
 */
private long truncateFile(String filename, long size)
        throws FileNotFoundException, IOException, NoModificationAllowedException {
    if (filename.startsWith("content://")) {
        throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
    }

    filename = FileHelper.getRealPath(filename, cordova);

    RandomAccessFile raf = new RandomAccessFile(filename, "rw");
    try {
        if (raf.length() >= size) {
            FileChannel channel = raf.getChannel();
            channel.truncate(size);
            return size;
        }

        return raf.length();
    } finally {
        raf.close();
    }
}

From source file:com.haulmont.cuba.core.sys.LogControlImpl.java

@Override
public String getTail(String fileName) throws LogControlException {
    // security check, supported only valid file names
    fileName = FilenameUtils.getName(fileName);

    StringBuilder sb = new StringBuilder();
    RandomAccessFile randomAccessFile = null;
    try {/* w w  w .j a v a2 s . c  o m*/
        File logFile = new File(logDir, fileName);
        if (!logFile.exists())
            throw new LogFileNotFoundException(fileName);

        randomAccessFile = new RandomAccessFile(logFile, "r");
        long lengthFile = randomAccessFile.length();
        if (lengthFile >= LOG_TAIL_AMOUNT_BYTES) {
            randomAccessFile.seek(lengthFile - LOG_TAIL_AMOUNT_BYTES);
            skipFirstLine(randomAccessFile);
        }
        while (randomAccessFile.read() != -1) {
            randomAccessFile.seek(randomAccessFile.getFilePointer() - 1);
            String line = readUtf8Line(randomAccessFile);
            if (line != null) {
                sb.append(line).append("\n");
            }
        }
    } catch (IOException e) {
        log.error("Error reading log file", e);
        throw new LogControlException("Error reading log file: " + fileName);
    } finally {
        if (randomAccessFile != null) {
            try {
                randomAccessFile.close();
            } catch (IOException ignored) {
            }
        }
    }
    return sb.toString();
}

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  ava2 s.  c  om*/
    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:com.koda.integ.hbase.storage.FileExtStorage.java

/**
 * Delete oldest file.// w ww .  ja va  2  s.c  o m
 */
public synchronized void deleteOldestFile() {

    LOG.info("[FileExtStorage] exceeded storage limit of " + maxStorageSize + ". Deleting "
            + getFilePath(minId.get()));
    File f = new File(getFilePath(minId.get()));

    long fileLength = f.length();
    boolean result = f.delete();
    if (result == false) {
        LOG.fatal("[FileExtStorage] Deleting " + getFilePath(minId.get()) + " failed.");
    } else {
        LOG.info("[FileExtStorage] Deleting " + getFilePath(minId.get()) + " succeeded.");
        //TODO: what to do if file deletion failed?   
        // Increment min id.
        Queue<RandomAccessFile> files = readers.remove(minId.get());
        // Remove from existed
        existedIds.remove(minId.get());

        if (files != null) {
            for (RandomAccessFile file : files) {

                try {
                    file.close();
                } catch (Exception e) {
                    // ignore?
                }
            }
        }

        currentStorageSize.addAndGet(-fileLength);
        minId.incrementAndGet();

    }
}