Example usage for java.io RandomAccessFile getFilePointer

List of usage examples for java.io RandomAccessFile getFilePointer

Introduction

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

Prototype

public native long getFilePointer() throws IOException;

Source Link

Document

Returns the current offset in this file.

Usage

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

/**
 * Read and decrypt the section starting at the current file offset.
 * Validates MAC of decrypted data, throwing if mismatch. When finished,
 * file offset is at the end of the entire section.
 *///  ww w  .  j  a v a2s . c o  m
private void readSection(RandomAccessFile f, OutputStream out) throws IOException, GeneralSecurityException {
    final long start = f.getFilePointer();

    final Section section = new Section();
    section.read(f);

    final IvParameterSpec ivSpec = new IvParameterSpec(section.iv);
    mCipher.init(Cipher.DECRYPT_MODE, mDataKey, ivSpec);
    mMac.init(mMacKey);

    byte[] inbuf = new byte[8192];
    byte[] outbuf;
    int n;
    while ((n = f.read(inbuf, 0, (int) Math.min(section.length, inbuf.length))) != -1) {
        section.length -= n;
        mMac.update(inbuf, 0, n);
        outbuf = mCipher.update(inbuf, 0, n);
        if (outbuf != null) {
            out.write(outbuf);
        }
        if (section.length == 0)
            break;
    }

    section.assertMac(mMac.doFinal());

    outbuf = mCipher.doFinal();
    if (outbuf != null) {
        out.write(outbuf);
    }
}

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

/**
 * Encrypt and write the given stream as a full section. Writes section
 * header and encrypted data starting at the current file offset. When
 * finished, file offset is at the end of the entire section.
 *///from   w ww  .j a v a  2  s. c om
private int writeSection(RandomAccessFile f, InputStream in) throws IOException, GeneralSecurityException {
    final long start = f.getFilePointer();

    // Write header; we'll come back later to finalize details
    final Section section = new Section();
    section.write(f);

    final long dataStart = f.getFilePointer();

    mRandom.nextBytes(section.iv);

    final IvParameterSpec ivSpec = new IvParameterSpec(section.iv);
    mCipher.init(Cipher.ENCRYPT_MODE, mDataKey, ivSpec);
    mMac.init(mMacKey);

    int plainLength = 0;
    byte[] inbuf = new byte[8192];
    byte[] outbuf;
    int n;
    while ((n = in.read(inbuf)) != -1) {
        plainLength += n;
        outbuf = mCipher.update(inbuf, 0, n);
        if (outbuf != null) {
            mMac.update(outbuf);
            f.write(outbuf);
        }
    }

    outbuf = mCipher.doFinal();
    if (outbuf != null) {
        mMac.update(outbuf);
        f.write(outbuf);
    }

    section.setMac(mMac.doFinal());

    final long dataEnd = f.getFilePointer();
    section.length = dataEnd - dataStart;

    // Rewind and update header
    f.seek(start);
    section.write(f);
    f.seek(dataEnd);

    return plainLength;
}

From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java

private boolean updateINIOnJDKUpgrade(String javaHome) {
    logger.debug("Updating INI file if JDK path is updated");
    RandomAccessFile file = null;
    boolean isUpdated = false;
    try {/*  w  w w.  j  av a2 s .  c  o m*/
        file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw");
        byte[] text = new byte[(int) file.length()];

        while (file.getFilePointer() != file.length()) {
            if (StringUtils.equals(file.readLine(), "-vm")) {
                String currentLine = file.readLine();
                if (StringUtils.equals(currentLine, javaHome)) {
                    logger.debug("JAVA_HOME and -vm in configuration file are same");
                } else {
                    logger.debug(
                            "JAVA_HOME and -vm in configuration file are different. Updating configuration file with JAVA_HOME");
                    file.seek(0);
                    file.readFully(text);
                    file.seek(0);
                    updateData(text, javaHome, currentLine, file);
                    isUpdated = true;
                }
                break;
            }
        }
    } catch (IOException ioException) {
        logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException);
    } finally {
        try {
            if (file != null) {
                file.close();
            }
        } catch (IOException ioException) {
            logger.error("IOException occurred while closing " + HYDROGRAPH_INI + " file", ioException);
        }
    }
    return isUpdated;
}

From source file:cern.acet.tracing.input.file.tailer.PositionTailer.java

/**
 * Read new lines./* w  ww  . j  a v a2 s  . co m*/
 *
 * @param reader The file to read
 * @return The new position after the lines have been read
 * @throws java.io.IOException if an I/O error occurs.
 */
private long readLines(RandomAccessFile reader) throws IOException {
    StringBuilder sb = new StringBuilder();

    long pos = reader.getFilePointer();
    long rePos = pos; // position to re-read

    int num;
    boolean seenCR = false;
    while (run && ((num = reader.read(inbuf)) != -1)) {
        for (int i = 0; i < num; i++) {
            byte ch = inbuf[i];
            switch (ch) {
            case '\n':
                seenCR = false; // swallow CR before LF
                listener.handle(sb.toString());
                sb.setLength(0);
                rePos = pos + i + 1;
                break;
            case '\r':
                if (seenCR) {
                    sb.append('\r');
                }
                seenCR = true;
                break;
            default:
                if (seenCR) {
                    seenCR = false; // swallow final CR
                    listener.handle(sb.toString());
                    sb.setLength(0);
                    rePos = pos + i + 1;
                }
                sb.append((char) ch); // add character, not its ascii value
            }
        }

        pos = reader.getFilePointer();
    }

    reader.seek(rePos); // Ensure we can re-read if necessary
    listener.positionUpdated(pos);
    return rePos;
}

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

protected void skipFirstLine(RandomAccessFile logFile) throws IOException {
    boolean eol = false;
    while (!eol) {
        switch (logFile.read()) {
        case -1://from  ww  w. jav  a 2 s. c  o m
        case '\n':
            eol = true;
            break;
        case '\r':
            eol = true;
            long cur = logFile.getFilePointer();
            if ((logFile.read()) != '\n') {
                logFile.seek(cur);
            }
            break;
        default:
            break;
        }
    }
}

From source file:com.aol.advertising.qiao.injector.file.AbstractFileReader.java

protected long checksum(RandomAccessFile raFile) throws IOException, IllegalStateException {
    long pos = raFile.getFilePointer();
    try {//from   ww  w .  j ava  2  s.c o m
        byte[] buffer = new byte[checksumByteLength];
        raFile.seek(0);
        int n = raFile.read(buffer);
        if (n < checksumByteLength) {
            String s;
            logger.warn(s = ("not enough data for checksum: current file size=" + n));
            throw new IllegalStateException(s);
        }

        synchronized (_crc) {
            _crc.reset();
            _crc.update(buffer);

            return _crc.getValue();
        }
    } finally {
        raFile.seek(pos);
    }

}

From source file:com.microsoft.azure.management.datalake.store.uploader.SingleSegmentUploader.java

/**
 * Reads the data into the buffer./* w  ww.  ja v  a2  s . co m*/
 *
 * @param inputStream The stream to read data from.
 * @param buffer The buffer to read data into
 * @param bufferOffset The offset in the buffer to begin pushing data
 * @param streamEndPosition The last point in the stream to read.
 * @return The number of bytes read into the buffer.
 * @throws IOException Thrown if there is an issue accessing the stream or the pointer to the file.
 */
private int readIntoBuffer(RandomAccessFile inputStream, byte[] buffer, int bufferOffset,
        long streamEndPosition) throws IOException {
    //read a block of data
    int bytesToRead = buffer.length - bufferOffset;
    if (bytesToRead > streamEndPosition - inputStream.getFilePointer()) {
        //last read may be smaller than previous reads; readjust # of bytes to read accordingly
        bytesToRead = (int) (streamEndPosition - inputStream.getFilePointer());
    }

    int remainingBytes = bytesToRead;

    while (remainingBytes > 0) {
        //Stream.Read may not read all the bytes we requested, so we need to retry until we filled up the entire buffer
        int bytesRead = inputStream.read(buffer, bufferOffset, remainingBytes);
        bufferOffset += bytesRead;
        remainingBytes = bytesToRead - bufferOffset;
    }

    return bytesToRead;
}

From source file:edu.msu.cme.rdp.readseq.readers.core.SFFCore.java

private LinkedHashMap<String, Long> readIndex() throws IOException {
    if (commonHeader.indexOffset <= commonHeader.headerLength) {
        throw new IOException("Index offset is not set correctly");
    }/*from   ww w .  j a va 2s .  c  o  m*/

    RandomAccessFile seqFile = super.getRawFile();

    long seekBackTo = seqFile.getFilePointer();
    seqFile.seek(commonHeader.indexOffset);
    long dataEnd = seqFile.getFilePointer();
    LinkedHashMap<String, Long> seqIndex = new LinkedHashMap(commonHeader.numReads);

    int magicNumber = seqFile.readInt();

    if (magicNumber == mftMagicNumber) {
        int version = seqFile.readInt();

        if (version != v1MagicNumber) {
            throw new IOException("Can only parse .mft v1.0 indices");
        }

        int xmlSize = seqFile.readInt();
        int dataSize = seqFile.readInt();
        dataEnd += dataSize;

        byte[] xml = new byte[xmlSize];
        seqFile.read(xml);
        manifest = new String(xml);

    } else if (magicNumber == srtMagicNumber) {
        int version = seqFile.readInt();

        if (version != v1MagicNumber) {
            throw new IOException("Can only parse .srt v1.0 indices");
        }

        if (seqFile.read() != 0) {
            throw new IOException("Failed to find expected null byte in .srt header");
        }
        dataEnd += commonHeader.indexLength;
    } else {
        throw new IOException("No supported index found");
    }

    List<Integer> currIndex = new ArrayList();
    while (seqFile.getFilePointer() < dataEnd) {
        int b = seqFile.readUnsignedByte();
        if (b == 0xff) {
            byte[] nameArray = new byte[currIndex.size() - 5];
            long indexLoc = 0;
            int[] multipliers = new int[] { 0, 16581375, 65025, 255, 1 };
            for (int i = 0; i < currIndex.size(); i++) {
                if (i < nameArray.length) {
                    nameArray[i] = (byte) (currIndex.get(i) & 0xff);
                } else {
                    int index = i - nameArray.length;
                    indexLoc += currIndex.get(i) * multipliers[index];
                }
            }
            String name = new String(nameArray);

            seqIndex.put(name, indexLoc);

            currIndex.clear();
        } else {
            currIndex.add(b);
        }
    }
    seqFile.seek(seekBackTo);

    return seqIndex;
}

From source file:TarList.java

public TarEntry(RandomAccessFile is) throws IOException, TarException {

    fileOffset = is.getFilePointer();

    // read() returns -1 at EOF
    if (is.read(name) < 0)
        throw new EOFException();
    // Tar pads to block boundary with nulls.
    if (name[0] == '\0')
        throw new EOFException();
    // OK, read remaining fields.
    is.read(mode);// w  w w .ja v  a 2s  . co  m
    is.read(uid);
    is.read(gid);
    is.read(size);
    is.read(mtime);
    is.read(chksum);
    type = is.readByte();
    is.read(linkName);
    is.read(magic);
    is.read(uname);
    is.read(gname);
    is.read(devmajor);
    is.read(devminor);

    // Since the tar header is < 512, we need to skip it.
    is.skipBytes((int) (TarFile.RECORDSIZE - (is.getFilePointer() % TarFile.RECORDSIZE)));

    // TODO if checksum() fails,
    //   throw new TarException("Failed to find next header");

}

From source file:com.excuseme.rocketleaguelivestats.scanner.tailer.Tailer.java

/**
 * Read new lines.//from   w w  w .  j a v a2s.co  m
 *
 * @param reader The file to read
 * @return The new position after the lines have been read
 * @throws java.io.IOException if an I/O error occurs.
 */
private long readLines(RandomAccessFile reader) throws IOException {
    StringBuilder sb = new StringBuilder();

    long pos = reader.getFilePointer();
    long rePos = pos; // position to re-read

    int num;
    boolean seenCR = false;
    while (run && ((num = reader.read(inbuf)) != -1)) {
        for (int i = 0; i < num; i++) {
            byte ch = inbuf[i];
            switch (ch) {
            case '\n':
                seenCR = false; // swallow CR before LF
                listener.handle(sb.toString());
                sb.setLength(0);
                rePos = pos + i + 1;
                break;
            case '\r':
                if (seenCR) {
                    sb.append('\r');
                }
                seenCR = true;
                break;
            default:
                if (seenCR) {
                    seenCR = false; // swallow final CR
                    listener.handle(sb.toString());
                    sb.setLength(0);
                    rePos = pos + i + 1;
                }
                sb.append((char) ch); // add character, not its ascii value
            }
        }

        pos = reader.getFilePointer();
    }
    if (reader.read(inbuf) == -1) {
        listener.endOfFile();
    }

    reader.seek(rePos); // Ensure we can re-read if necessary
    return rePos;
}