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:org.apache.jackrabbit.core.value.BLOBInTempFile.java

public int read(byte[] b, long position) throws IOException, RepositoryException {
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    try {//  w w  w.  java2 s .c  o m
        raf.seek(position);
        return raf.read(b);
    } finally {
        raf.close();
    }
}

From source file:org.apache.hadoop.chukwa.datacollection.adaptor.filetailer.RCheckFTAdaptor.java

@Override
public boolean tailFile() throws InterruptedException {
    boolean hasMoreData = false;
    try {// w  w w  . j  a  v  a 2 s .co  m

        if (caughtUp) {
            //we're caught up and watching an unrotated file
            mkFileQ(); //figure out what to watch
            advanceQ();
        }
        if (cur == null) //file we're watching doesn't exist
            return false;

        long len = cur.length();
        long tsPreTail = cur.exists() ? cur.lastModified() : prevFileLastModDate;

        if (log.isDebugEnabled())
            log.debug(adaptorID + " treating " + cur + " as " + toWatch + " len = " + len);

        if (len < fileReadOffset) {
            log.info("file " + cur + " shrank from " + fileReadOffset + " to " + len);
            //no unseen changes to prev version, since mod date is older than last scan.
            offsetOfFirstByte += fileReadOffset;
            fileReadOffset = 0;
        } else if (len > fileReadOffset) {
            log.debug("slurping from " + cur + " at offset " + fileReadOffset);
            RandomAccessFile reader = new RandomAccessFile(cur, "r");
            slurp(len, reader);
            reader.close();
        } else {
            //we're either caught up or at EOF
            if (!caughtUp) {
                prevFileLastModDate = cur.lastModified();
                //Hit EOF on an already-rotated file. Move on!
                offsetOfFirstByte += fileReadOffset;
                fileReadOffset = 0;
                advanceQ();
                log.debug("not caught up, and hit EOF.  Moving forward in queue to " + cur);
            } else
                prevFileLastModDate = tsPreTail;

        }

    } catch (IOException e) {
        log.warn("IOException in " + adaptorID, e);
        deregisterAndStop();
    }

    return hasMoreData;
}

From source file:Main.java

public static Bitmap convertToMutable(Bitmap srcBitmap, String cacheDirPath, String tempFileName) {
    try {/*from   w w w  .  jav  a2s . com*/
        // this is the file going to use temporally to save the bytes.
        // This file will not be a image, it will store the raw image data.
        int index = tempFileName.lastIndexOf(".");
        if (index != -1)
            tempFileName = tempFileName.substring(0, index);
        File file = new File(cacheDirPath + File.separator + tempFileName + ".tmp");

        // Open an RandomAccessFile
        // Make sure you have added uses-permission
        // android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        // into AndroidManifest.xml file
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

        // get the width and height of the source bitmap.
        int width = srcBitmap.getWidth();
        int height = srcBitmap.getHeight();
        Config type = srcBitmap.getConfig();

        // Copy the byte to the file
        // Assume source bitmap loaded using options.inPreferredConfig =
        // Config.ARGB_8888;
        FileChannel channel = randomAccessFile.getChannel();
        MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, srcBitmap.getRowBytes() * height);
        srcBitmap.copyPixelsToBuffer(map);
        // recycle the source bitmap, this will be no longer used.
        srcBitmap.recycle();
        System.gc();// try to force the bytes from the imgIn to be released

        // Create a new bitmap to load the bitmap again. Probably the memory
        // will be available.
        srcBitmap = Bitmap.createBitmap(width, height, type);
        map.position(0);
        // load it back from temporary
        srcBitmap.copyPixelsFromBuffer(map);
        // close the temporary file and channel , then delete that also
        channel.close();
        randomAccessFile.close();

        // delete the temp file
        file.delete();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return srcBitmap;
}

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

/**
 * Regression test for HDFS-8965 which verifies that
 * FSEditLogFileInputStream#scanOp verifies Op checksums.
 *///from w  ww . j a v a2  s . c  o  m
@Test(timeout = 60000)
public void testScanCorruptEditLog() throws Exception {
    Configuration conf = new Configuration();
    File editLog = new File(System.getProperty("test.build.data", "/tmp"), "testCorruptEditLog");

    LOG.debug("Creating test edit log file: " + editLog);
    EditLogFileOutputStream elos = new EditLogFileOutputStream(conf, editLog.getAbsoluteFile(), 8192);
    elos.create(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);
    FSEditLogOp.OpInstanceCache cache = new FSEditLogOp.OpInstanceCache();
    FSEditLogOp.MkdirOp mkdirOp = FSEditLogOp.MkdirOp.getInstance(cache);
    mkdirOp.reset();
    mkdirOp.setRpcCallId(123);
    mkdirOp.setTransactionId(1);
    mkdirOp.setInodeId(789L);
    mkdirOp.setPath("/mydir");
    PermissionStatus perms = PermissionStatus.createImmutable("myuser", "mygroup",
            FsPermission.createImmutable((short) 0777));
    mkdirOp.setPermissionStatus(perms);
    elos.write(mkdirOp);
    mkdirOp.reset();
    mkdirOp.setRpcCallId(456);
    mkdirOp.setTransactionId(2);
    mkdirOp.setInodeId(123L);
    mkdirOp.setPath("/mydir2");
    perms = PermissionStatus.createImmutable("myuser", "mygroup", FsPermission.createImmutable((short) 0666));
    mkdirOp.setPermissionStatus(perms);
    elos.write(mkdirOp);
    elos.setReadyToFlush();
    elos.flushAndSync(false);
    elos.close();
    long fileLen = editLog.length();

    LOG.debug("Corrupting last 4 bytes of edit log file " + editLog + ", whose length is " + fileLen);
    RandomAccessFile rwf = new RandomAccessFile(editLog, "rw");
    rwf.seek(fileLen - 4);
    int b = rwf.readInt();
    rwf.seek(fileLen - 4);
    rwf.writeInt(b + 1);
    rwf.close();

    EditLogFileInputStream elis = new EditLogFileInputStream(editLog);
    Assert.assertEquals(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION, elis.getVersion(true));
    Assert.assertEquals(1, elis.scanNextOp());
    LOG.debug("Read transaction 1 from " + editLog);
    try {
        elis.scanNextOp();
        Assert.fail("Expected scanNextOp to fail when op checksum was corrupt.");
    } catch (IOException e) {
        LOG.debug("Caught expected checksum error when reading corrupt " + "transaction 2", e);
        GenericTestUtils.assertExceptionContains("Transaction is corrupt.", e);
    }
    elis.close();
}

From source file:com.liferay.faces.bridge.renderkit.primefaces.internal.PrimeFacesFileItem.java

public byte[] get() {

    byte[] bytes = null;

    try {//from  ww  w .  j  av a2  s.  c  o  m
        File file = new File(uploadedFile.getAbsolutePath());

        if (file.exists()) {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
            bytes = new byte[(int) randomAccessFile.length()];
            randomAccessFile.readFully(bytes);
            randomAccessFile.close();
            file.delete();
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return bytes;
}

From source file:com.btoddb.fastpersitentqueue.JournalFileTest.java

@Test
public void testInvalidHeaderVersion() throws Exception {
    JournalFile jf1 = new JournalFile(theFile);
    jf1.initForWriting(new UUID());
    jf1.close();//w w  w .j  a  va2s  . c  om

    // mess up the UUID
    RandomAccessFile raFile = new RandomAccessFile(theFile, "rw");
    Utils.writeInt(raFile, 2);
    raFile.close();
    //        Utils.writeUuidToFile(raFile, id);
    //        Utils.writeLong(raFile, numberOfEntries.get());

    JournalFile jf2 = new JournalFile(theFile);
    try {
        jf2.initForReading();
        fail("should have found invalid journal version");
    } catch (FpqException e) {
        assertThat(e.getMessage(), containsString("invalid journal file version"));
    }
}

From source file:org.apache.archiva.common.filelock.DefaultFileLockManager.java

private void closeQuietly(RandomAccessFile randomAccessFile) {
    if (randomAccessFile == null) {
        return;/*ww w  . j  a  v  a  2 s . c om*/
    }

    try {
        randomAccessFile.close();
    } catch (IOException e) {
        // ignore
    }
}

From source file:com.example.android.vault.EncryptedDocumentTest.java

public void testBitTwiddle() throws Exception {
    final EncryptedDocument doc = new EncryptedDocument(4, mFile, mDataKey, mMacKey);

    // write some metadata
    final JSONObject before = new JSONObject();
    before.put("twiddle", "twiddle");
    doc.writeMetadataAndContent(before, null);

    final RandomAccessFile f = new RandomAccessFile(mFile, "rw");
    f.seek(f.length() - 4);// w  w w .j av  a  2 s .com
    f.write(0x00);
    f.close();

    try {
        doc.readMetadata();
        fail("somehow passed hmac");
    } catch (DigestException expected) {
    }
}

From source file:com.koda.integ.hbase.storage.FIFOStorageRecycler.java

public void run() {
    LOG.info(Thread.currentThread().getName() + " started.");

    while (needContinue()) {
        // Get oldest file      
        int minId = storage.getMinId().get();
        String fileName = storage.getFilePath(minId);
        RandomAccessFile raf = storage.getFile(minId);

        try {//from w  w  w  . ja v a2s.co m
            long size = raf.length();
            raf.close();
            // STATISTICS
            totalFilesSize.addAndGet(size);
            LOG.info("Processing file: " + fileName + " size=" + size);
            // STATISTICS
            totalScannedFiles.incrementAndGet();
            // Update current storage size
            storage.deleteOldestFile();
        } catch (Exception e) {
            LOG.error(fileName, e);
        }

    }
    LOG.info(Thread.currentThread().getName() + " stopped.");
}

From source file:com.btoddb.fastpersitentqueue.MemorySegmentSerializer.java

public MemorySegment loadHeaderOnly(String fn) throws IOException {
    File theFile = new File(directory, fn);
    RandomAccessFile raFile = new RandomAccessFile(theFile, "r");
    try {//from w w w . j  a  va  2s . c  o  m
        MemorySegment segment = new MemorySegment();
        segment.readHeaderFromDisk(raFile);
        return segment;
    } finally {
        raFile.close();
    }
}