Example usage for java.io RandomAccessFile seek

List of usage examples for java.io RandomAccessFile seek

Introduction

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

Prototype

public void seek(long pos) throws IOException 

Source Link

Document

Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

Usage

From source file:com.vincestyling.netroid.request.FileDownloadRequest.java

/**
 * In this method, we got the Content-Length, with the TemporaryFile length,
 * we can calculate the actually size of the whole file, if TemporaryFile not exists,
 * we'll take the store file length then compare to actually size, and if equals,
 * we consider this download was already done.
 * We used {@link RandomAccessFile} to continue download, when download success,
 * the TemporaryFile will be rename to StoreFile.
 *//*from   ww  w.  j  a v  a 2  s  .  c  om*/
@Override
public byte[] handleResponse(HttpResponse response, Delivery delivery) throws IOException, ServerError {
    // Content-Length might be negative when use HttpURLConnection because it default header Accept-Encoding is gzip,
    // we can force set the Accept-Encoding as identity in prepare() method to slove this problem but also disable gzip response.
    HttpEntity entity = response.getEntity();
    long fileSize = entity.getContentLength();
    if (fileSize <= 0) {
        NetroidLog.d("Response doesn't present Content-Length!");
    }

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

        // Verify the Content-Range Header, to ensure temporary file is part of the whole file.
        // Sometime, temporary file length add response content-length might greater than actual file length,
        // in this situation, we consider the temporary file is invalid, then throw an exception.
        String realRangeValue = HttpUtils.getHeader(response, "Content-Range");
        // response Content-Range may be null when "Range=bytes=0-"
        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 + "].");
            }
        }
    }

    // Compare the store file size(after download successes have) to server-side Content-Length.
    // temporary file will rename to store file after download success, so we compare the
    // Content-Length to ensure this request already download or not.
    if (fileSize > 0 && mStoreFile.length() == fileSize) {
        // Rename the store file to temporary file, mock the download success. ^_^
        mStoreFile.renameTo(mTemporaryFile);

        // Deliver download progress.
        delivery.postDownloadProgress(this, fileSize, fileSize);

        return null;
    }

    RandomAccessFile tmpFileRaf = new RandomAccessFile(mTemporaryFile, "rw");

    // If server-side support range download, we seek to last point of the temporary file.
    if (isSupportRange) {
        tmpFileRaf.seek(downloadedSize);
    } else {
        // If not, truncate the temporary file then start download from beginning.
        tmpFileRaf.setLength(0);
        downloadedSize = 0;
    }

    InputStream in = null;
    try {
        in = entity.getContent();
        // Determine the response gzip encoding, support for HttpClientStack download.
        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;
            delivery.postDownloadProgress(this, fileSize, downloadedSize);

            if (isCanceled()) {
                delivery.postCancel(this);
                break;
            }
        }
    } finally {
        try {
            // Close the InputStream
            if (in != null)
                in.close();
        } catch (Exception e) {
            NetroidLog.v("Error occured when calling InputStream.close");
        }

        try {
            // release the resources by "consuming the content".
            entity.consumeContent();
        } catch (Exception e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            NetroidLog.v("Error occured when calling consumingContent");
        }
        tmpFileRaf.close();
    }

    return null;
}

From source file:org.apache.jackrabbit.oak.segment.file.TarReader.java

/**
 * Tries to read an existing index from the given tar file. The index is
 * returned if it is found and looks valid (correct checksum, passes
 * sanity checks).// ww  w  .j  av a 2 s  . com
 *
 * @param file tar file
 * @param name name of the tar file, for logging purposes
 * @return tar index, or {@code null} if not found or not valid
 * @throws IOException if the tar file could not be read
 */
private static ByteBuffer loadAndValidateIndex(RandomAccessFile file, String name) throws IOException {
    long length = file.length();
    if (length % BLOCK_SIZE != 0 || length < 6 * BLOCK_SIZE || length > Integer.MAX_VALUE) {
        log.warn("Unexpected size {} of tar file {}", length, name);
        return null; // unexpected file size
    }

    // read the index metadata just before the two final zero blocks
    ByteBuffer meta = ByteBuffer.allocate(16);
    file.seek(length - 2 * BLOCK_SIZE - 16);
    file.readFully(meta.array());
    int crc32 = meta.getInt();
    int count = meta.getInt();
    int bytes = meta.getInt();
    int magic = meta.getInt();

    if (magic != INDEX_MAGIC) {
        return null; // magic byte mismatch
    }

    if (count < 1 || bytes < count * TarEntry.SIZE + 16 || bytes % BLOCK_SIZE != 0) {
        log.warn("Invalid index metadata in tar file {}", name);
        return null; // impossible entry and/or byte counts
    }

    // this involves seeking backwards in the file, which might not
    // perform well, but that's OK since we only do this once per file
    ByteBuffer index = ByteBuffer.allocate(count * TarEntry.SIZE);
    file.seek(length - 2 * BLOCK_SIZE - 16 - count * TarEntry.SIZE);
    file.readFully(index.array());
    index.mark();

    CRC32 checksum = new CRC32();
    long limit = length - 2 * BLOCK_SIZE - bytes - BLOCK_SIZE;
    long lastmsb = Long.MIN_VALUE;
    long lastlsb = Long.MIN_VALUE;
    byte[] entry = new byte[TarEntry.SIZE];
    for (int i = 0; i < count; i++) {
        index.get(entry);
        checksum.update(entry);

        ByteBuffer buffer = wrap(entry);
        long msb = buffer.getLong();
        long lsb = buffer.getLong();
        int offset = buffer.getInt();
        int size = buffer.getInt();

        if (lastmsb > msb || (lastmsb == msb && lastlsb > lsb)) {
            log.warn("Incorrect index ordering in tar file {}", name);
            return null;
        } else if (lastmsb == msb && lastlsb == lsb && i > 0) {
            log.warn("Duplicate index entry in tar file {}", name);
            return null;
        } else if (offset < 0 || offset % BLOCK_SIZE != 0) {
            log.warn("Invalid index entry offset in tar file {}", name);
            return null;
        } else if (size < 1 || offset + size > limit) {
            log.warn("Invalid index entry size in tar file {}", name);
            return null;
        }

        lastmsb = msb;
        lastlsb = lsb;
    }

    if (crc32 != (int) checksum.getValue()) {
        log.warn("Invalid index checksum in tar file {}", name);
        return null; // checksum mismatch
    }

    index.reset();
    return index;
}

From source file:TestFuseDFS.java

/**
 * Test random access to a file//w  w  w  .  jav a  2s.c om
 */
@Test
public void testRandomAccess() throws IOException {
    final String contents = "hello world";
    File f = new File(mountPoint, "file1");

    createFile(f, contents);

    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(f.length());
    try {
        raf.write('b');
    } catch (IOException e) {
        // Expected: fuse-dfs not yet support append
        assertEquals("Operation not supported", e.getMessage());
    } finally {
        raf.close();
    }

    raf = new RandomAccessFile(f, "rw");
    raf.seek(0);
    try {
        raf.write('b');
        fail("Over-wrote existing bytes");
    } catch (IOException e) {
        // Expected: can-not overwrite a file
        assertEquals("Invalid argument", e.getMessage());
    } finally {
        raf.close();
    }
    execAssertSucceeds("rm " + f.getAbsolutePath());
}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
 * We have the password from initializing the class. pass the iv and salt here which is
 * obtained when encrypting the file initially.
 *
 * @param inFile - The Encrypted File containing encrypted data , salt and InitVec
 * @throws NoSuchAlgorithmException//from  w  ww. j a v  a  2 s .  c  o m
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 * @throws IOException
 */
public void setupDecrypt(File inFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, DecoderException, IOException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    byte[] vSalt = new byte[8];
    byte[] vInitVec = new byte[16];

    RandomAccessFile vFile = new RandomAccessFile(inFile, "rw");

    //The last 8 bits are salt so seek to length of file minus 9 bits
    vFile.seek(vFile.length() - 8);
    vFile.readFully(vSalt);

    //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24
    //Thus to seek to length of file minus 24 bits
    vFile.seek(vFile.length() - 24);
    vFile.readFully(vInitVec);
    vFile.seek(0);

    File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file");

    RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw");

    for (int i = 0; i < (vFile.length() - 24); ++i) {
        vTmpFile.write(vFile.readByte());
    }
    vFile.close();
    vTmpFile.close();

    inFile.delete();
    tmpFile.renameTo(inFile);

    Db("got salt " + Hex.encodeHexString(vSalt));

    Db("got initvector :" + Hex.encodeHexString(vInitVec));

    /* Derive the key, given password and salt. */
    // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
    // The end user must also install them (not compiled in) so beware.
    // see here:
    // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
    // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function
    //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard)

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);

    tmp = factory.generateSecret(spec);
    secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    // Decrypt the message, given derived key and initialization vector.
    vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec));
}

From source file:edu.harvard.i2b2.adminTool.dataModel.PatientMappingFactory.java

public static void append(RandomAccessFile f, String outString) throws IOException {
    try {/*  w  w  w .ja  va2 s .c  o m*/
        f.seek(f.length());
        f.writeBytes(outString);
    } catch (IOException e) {
        throw new IOException("trouble writing to random access file.");
    }
    return;
}

From source file:org.apache.sling.commons.log.logback.internal.Tailer.java

/**
 * Returns the starting position of UNIX "tail -n".
 *///from  ww w . j  av  a  2s .c om
private long getTailStartPos(RandomAccessFile file, int n) throws IOException {
    int newlineCount = 0;
    long length = file.length();
    long pos = length - BUFFER_SIZE;
    int buffLength = BUFFER_SIZE;

    if (pos < 0) {
        pos = 0;
        buffLength = (int) length;
    }

    while (true) {
        file.seek(pos);
        file.readFully(buffer, 0, buffLength);

        for (int i = buffLength - 1; i >= 0; i--) {
            if ((char) buffer[i] == '\n') {
                newlineCount++;

                if (newlineCount >= n) {
                    pos += (i + 1);
                    return pos;
                }
            }
        }

        if (pos == 0) {
            break;
        }

        if (pos - BUFFER_SIZE < 0) {
            buffLength = (int) pos;
            pos = 0;
        } else {
            pos -= BUFFER_SIZE;
        }
    }

    return pos;
}

From source file:at.tuwien.minimee.util.TopParser.java

/**
 * The process ID is in the last line of the file and looks like follows:
 * monitored_pid= 6738 //from   www  . j  ava  2s.c  om
 * 
 * @param input
 * @return
 * @throws Exception
 */
private Integer findPid() throws Exception {

    Integer pid = new Integer(0);

    // we open the file
    RandomAccessFile f = new RandomAccessFile(file, "r");

    try {

        long size = f.length();

        f.seek(size - 2);

        // we search the file reverse for '='
        byte[] b = new byte[1];
        for (long i = size - 2; i >= 0; i--) {
            f.seek(i);
            f.read(b);
            if (b[0] == '=') {
                break;
            }
        }

        String line = f.readLine().trim();

        pid = new Integer(line);

    } finally {
        // this is important, RandomAccessFile doesn't close the file handle by default!
        // if close isn't called, you'll get very soon 'too many open files'
        f.close();
    }

    return pid;
}

From source file:com.metamesh.opencms.rfs.RfsAwareDumpLoader.java

/**
 * @see org.opencms.loader.I_CmsResourceLoader#load(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//* w ww.  ja  v a 2  s.  c om*/
public void load(CmsObject cms, CmsResource resource, HttpServletRequest req, HttpServletResponse res)
        throws IOException, CmsException {

    if (!(resource instanceof RfsCmsResource)) {
        super.load(cms, resource, req, res);
        return;
    }

    if (canSendLastModifiedHeader(resource, req, res)) {
        // no further processing required
        return;
    }

    if (CmsWorkplaceManager.isWorkplaceUser(req)) {
        // prevent caching for Workplace users
        res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis());
        CmsRequestUtil.setNoCacheHeaders(res);
    }

    RfsCmsResource rfsFile = (RfsCmsResource) resource;
    File f = rfsFile.getRfsFile();

    if (f.getName().toLowerCase().endsWith("webm")) {
        res.setHeader("Content-Type", "video/webm");
    } else if (f.getName().toLowerCase().endsWith("ogv")) {
        res.setHeader("Content-Type", "video/ogg");
    } else if (f.getName().toLowerCase().endsWith("mp4")) {
        res.setHeader("Content-Type", "video/mp4");
    }

    if (req.getMethod().equalsIgnoreCase("HEAD")) {
        res.setStatus(HttpServletResponse.SC_OK);
        res.setHeader("Accept-Ranges", "bytes");
        res.setContentLength((int) f.length());
        return;
    } else if (req.getMethod().equalsIgnoreCase("GET")) {
        if (req.getHeader("Range") != null) {

            String range = req.getHeader("Range");

            String[] string = range.split("=")[1].split("-");
            long start = Long.parseLong(string[0]);
            long end = string.length == 1 ? f.length() - 1 : Long.parseLong(string[1]);
            long length = end - start + 1;

            res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

            res.setHeader("Accept-Ranges", "bytes");
            res.setHeader("Content-Length", "" + length);
            res.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + f.length());

            RandomAccessFile ras = null;

            try {
                ras = new RandomAccessFile(f, "r");
                ras.seek(start);
                final int chunkSize = 4096;
                byte[] buffy = new byte[chunkSize];
                int nextChunkSize = length > chunkSize ? chunkSize : (int) length;
                long bytesLeft = length;
                while (bytesLeft > 0) {
                    ras.read(buffy, 0, nextChunkSize);
                    res.getOutputStream().write(buffy, 0, nextChunkSize);
                    res.getOutputStream().flush();
                    bytesLeft = bytesLeft - nextChunkSize;
                    nextChunkSize = bytesLeft > chunkSize ? chunkSize : (int) bytesLeft;

                    /*
                     * to simulate lower bandwidth
                     */
                    /*
                    try {
                      Thread.sleep(10);
                    } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    }
                    */
                }
            } finally {
                if (ras != null) {
                    ras.close();
                }
            }
            return;
        }
    }

    res.setStatus(HttpServletResponse.SC_OK);
    res.setHeader("Accept-Ranges", "bytes");
    res.setContentLength((int) f.length());
    service(cms, resource, req, res);
}

From source file:com.sky.drovik.player.media.DiskCache.java

public void put(long key, byte[] data, long timestamp) {
    // Check to see if the record already exists.
    Record record = null;/*from   ww w  .  jav  a2  s.  com*/
    synchronized (mIndexMap) {
        record = mIndexMap.get(key);
    }
    if (record != null && data.length <= record.sizeOnDisk) {
        // We just replace the chunk.
        int currentChunk = record.chunk;
        try {
            RandomAccessFile chunkFile = getChunkFile(record.chunk);
            if (chunkFile != null) {
                chunkFile.seek(record.offset);
                chunkFile.write(data);
                synchronized (mIndexMap) {
                    mIndexMap.put(key,
                            new Record(currentChunk, record.offset, data.length, record.sizeOnDisk, timestamp));
                }
                if (++mNumInsertions == 32) { // CR: 32 => constant
                    // Flush the index file at a regular interval. To avoid
                    // writing the entire
                    // index each time the format could be changed to an
                    // append-only journal with
                    // a snapshot generated on exit.
                    flush();
                }
                return;
            }
        } catch (Exception e) {
            Log.e(TAG, "Unable to read from chunk file");
        }
    }
    // Append a new chunk to the current chunk.
    final int chunk = mTailChunk;
    final RandomAccessFile chunkFile = getChunkFile(chunk);
    if (chunkFile != null) {
        try {
            final int offset = (int) chunkFile.length();
            chunkFile.seek(offset);
            chunkFile.write(data);
            synchronized (mIndexMap) {
                mIndexMap.put(key, new Record(chunk, offset, data.length, data.length, timestamp));
            }
            if (offset + data.length > CHUNK_SIZE) {
                ++mTailChunk;
            }

            if (++mNumInsertions == 32) { // CR: 32 => constant
                // Flush the index file at a regular interval. To avoid
                // writing the entire
                // index each time the format could be changed to an
                // append-only journal with
                // a snapshot generated on exit.
                flush();
            }
        } catch (IOException e) {
            Log.e(TAG, "Unable to write new entry to chunk file");
        }
    } else {
        Log.e(TAG, "getChunkFile() returned null");
    }
}

From source file:org.kalypso.shape.shp.SHPFile.java

/**
 * Adds a new shape entry to the end of the file.<br>
 * This method is atomic in that sense that if an exception occurs while a shape convertet to bytes, inetad a
 * Null-Shape will be written./*from w  w w . ja  va2s .  co m*/
 */
public SHXRecord addShape(final ISHPGeometry shape, final int recordNumber) throws IOException, SHPException {
    if (shape == null)
        throw new SHPException("shape == null not allowed. Add SHPNullShape instead.");

    if (!(shape instanceof SHPNullShape) && shape.getType() != getShapeType())
        throw new SHPException("Cannot add shape, wrong type.");

    final RandomAccessFile raf = getRandomAccessFile();

    final long currentFileLength = raf.length();

    /* Convert shape into bytes and write them in one go */
    final byte[] bytes = writeRecordAsBytes(recordNumber, shape);
    raf.seek(currentFileLength);
    raf.write(bytes);

    /* Update header */
    final SHPEnvelope shapeMbr = shape.getEnvelope();
    expandMbr(shapeMbr);

    /* Create and return index record */
    final int contentLength = bytes.length - RECORD_HEADER_BYTES;
    return new SHXRecord((int) currentFileLength / 2, contentLength / 2);
}