Example usage for java.io RandomAccessFile readFully

List of usage examples for java.io RandomAccessFile readFully

Introduction

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

Prototype

public final void readFully(byte b[]) throws IOException 

Source Link

Document

Reads b.length bytes from this file into the byte array, starting at the current file pointer.

Usage

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

public byte[] get(long key, long timestamp) {
    // Look up the record for the given key.
    Record record = null;/* w w w  .  j  av  a 2  s  . c  om*/
    synchronized (mIndexMap) {
        record = mIndexMap.get(key);
    }
    if (record != null) {
        // Read the chunk from the file.
        if (record.timestamp < timestamp) {
            Log.i(TAG, "File has been updated to " + timestamp + " since the last time " + record.timestamp
                    + " stored in cache.");
            return null;
        }
        try {
            RandomAccessFile chunkFile = getChunkFile(record.chunk);
            if (chunkFile != null) {
                byte[] data = new byte[record.size];
                chunkFile.seek(record.offset);
                chunkFile.readFully(data);
                return data;
            }
        } catch (Exception e) {
            Log.e(TAG, "Unable to read from chunk file");
        }
    }
    return null;
}

From source file:azkaban.common.utils.Utils.java

/**
 * Read in content of a file and get the last *lineCount* lines. It is
 * equivalent to *tail* command/*from   ww w .ja v a 2  s . c  om*/
 * 
 * @param filename
 * @param lineCount
 * @param chunkSize
 * @return
 */
public static Vector<String> tail(String filename, int lineCount, int chunkSize) {
    try {
        // read in content of the file
        RandomAccessFile file = new RandomAccessFile(filename, "r");
        // destination vector
        Vector<String> lastNLines = new Vector<String>();
        // current position
        long currPos = file.length() - 1;
        long startPos;
        byte[] byteArray = new byte[chunkSize];

        // read in content of the file in reverse order
        while (true) {
            // read in from *fromPos*
            startPos = currPos - chunkSize;

            if (startPos <= 0) { // toward the beginning of the file
                file.seek(0);
                file.read(byteArray, 0, (int) currPos); // only read in
                                                        // curPos bytes
                parseLinesFromLast(byteArray, 0, (int) currPos, lineCount, lastNLines);
                break;
            } else {
                file.seek(startPos);
                if (byteArray == null)
                    byteArray = new byte[chunkSize];
                file.readFully(byteArray);
                if (parseLinesFromLast(byteArray, lineCount, lastNLines)) {
                    break; // we got the last *lineCount* lines
                }

                // move the current position
                currPos = startPos; // + lastLine.getBytes().length;
            }
        }

        // there might be lineCount + 1 lines and the first line (now it is the last line)
        // might not be complete
        for (int index = lineCount; index < lastNLines.size(); index++)
            lastNLines.removeElementAt(index);

        // reverse the order of elements in lastNLines
        Collections.reverse(lastNLines);
        return lastNLines;
    } catch (Exception e) {
        return null;
    }

}

From source file:hudson.util.TextFile.java

/**
 * Efficiently reads the last N characters (or shorter, if the whole file is shorter than that.)
 *
 * <p>/*from w w w  .j  a  v a  2 s  .  c om*/
 * This method first tries to just read the tail section of the file to get the necessary chars.
 * To handle multi-byte variable length encoding (such as UTF-8), we read a larger than
 * necessary chunk.
 *
 * <p>
 * Some multi-byte encoding, such as Shift-JIS (http://en.wikipedia.org/wiki/Shift_JIS) doesn't
 * allow the first byte and the second byte of a single char to be unambiguously identified,
 * so it is possible that we end up decoding incorrectly if we start reading in the middle of a multi-byte
 * character. All the CJK multi-byte encodings that I know of are self-correcting; as they are ASCII-compatible,
 * any ASCII characters or control characters will bring the decoding back in sync, so the worst
 * case we just have some garbage in the beginning that needs to be discarded. To accommodate this,
 * we read additional 1024 bytes.
 *
 * <p>
 * Other encodings, such as UTF-8, are better in that the character boundary is unambiguous,
 * so there can be at most one garbage char. For dealing with UTF-16 and UTF-32, we read at
 * 4 bytes boundary (all the constants and multipliers are multiples of 4.)
 *
 * <p>
 * Note that it is possible to construct a contrived input that fools this algorithm, and in this method
 * we are willing to live with a small possibility of that to avoid reading the whole text. In practice,
 * such an input is very unlikely.
 *
 * <p>
 * So all in all, this algorithm should work decently, and it works quite efficiently on a large text.
 */
public @Nonnull String fastTail(int numChars, Charset cs) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(file, "r");

    try {
        long len = raf.length();
        // err on the safe side and assume each char occupies 4 bytes
        // additional 1024 byte margin is to bring us back in sync in case we started reading from non-char boundary.
        long pos = Math.max(0, len - (numChars * 4 + 1024));
        raf.seek(pos);

        byte[] tail = new byte[(int) (len - pos)];
        raf.readFully(tail);

        String tails = cs.decode(java.nio.ByteBuffer.wrap(tail)).toString();

        return new String(tails.substring(Math.max(0, tails.length() - numChars))); // trim the baggage of substring by allocating a new String
    } finally {
        raf.close();
    }
}

From source file:name.martingeisse.stackd.server.section.storage.FolderBasedSectionStorage.java

/**
 * /*  w ww .  ja  va 2s.  co  m*/
 */
private boolean loadSectionFromFile(final OutputStream out, final RandomAccessFile access, final int tocIndex)
        throws IOException {

    // read the ToC entry
    access.seek(tocIndex * 12);
    final int dataStartAddress = access.readInt();
    final int dataSize = access.readInt();
    /* int dataFlags = */access.readInt();

    // handle missing sections
    if (dataStartAddress < 1) {
        return false;
    }

    // read the data
    final byte[] compressedCubeData = new byte[dataSize];
    access.seek(dataStartAddress);
    access.readFully(compressedCubeData);

    // write data to the stream
    out.write(compressedCubeData);

    return true;

}

From source file:com.sun.faban.harness.webclient.ResultAction.java

private String editResultInfo(String runID) throws FileNotFoundException, IOException {
    RunId runId = new RunId(runID);
    String ts = null;/*from   w w w .j a v a2 s . co  m*/
    String[] status = new String[2];
    File file = new File(Config.OUT_DIR + runID + '/' + Config.RESULT_INFO);
    RandomAccessFile rf = new RandomAccessFile(file, "rwd");
    long size = rf.length();
    byte[] buffer = new byte[(int) size];
    rf.readFully(buffer);
    String content = new String(buffer, 0, (int) size);
    int idx = content.indexOf('\t');
    if (idx != -1) {
        status[0] = content.substring(0, idx).trim();
        status[1] = content.substring(++idx).trim();
    } else {
        status[0] = content.trim();
        int lastIdxln = status[0].lastIndexOf("\n");
        if (lastIdxln != -1)
            status[0] = status[0].substring(0, lastIdxln - 1);
    }
    if (status[1] != null) {
        ts = status[1];
    } else {
        String paramFileName = runId.getResultDir().getAbsolutePath() + File.separator + "run.xml";
        File paramFile = new File(paramFileName);
        long dt = paramFile.lastModified();
        ts = dateFormat.format(new Date(dt));
        rf.seek(rf.length());
        rf.writeBytes('\t' + ts.trim());
    }
    rf.close();
    return ts;
}

From source file:org.commoncrawl.service.listcrawler.HDFSFileIndex.java

private HDFSFileIndex.IndexDataBlock demandLoadIndexDataBlock(long fingerprint, int itemDataOffset,
        int itemDataSize) throws IOException {
    // ok time to load this block ...
    RandomAccessFile file = new RandomAccessFile(_localIndexFilePath, "r");

    try {/*from  w w w .j  a va  2 s .c o  m*/

        ByteBuffer bufferOut = ByteBuffer.allocate(itemDataSize);

        if (bufferOut != null) {
            file.seek(_indexDataOffset + itemDataOffset);
            file.readFully(bufferOut.array());
            HDFSFileIndex.IndexDataBlock dataBlock = new IndexDataBlock(fingerprint, 0, bufferOut);
            return dataBlock;
        } else {
            throw new IOException("Unable to allocate byte buffer!!!");
        }
    } finally {
        if (file != null) {
            file.close();
        }
    }
}

From source file:org.kchine.r.server.RListener.java

public static void pager(String fileName, String header, String title, String deleteFile) {
    HashMap<String, Object> attributes = new HashMap<String, Object>();

    byte[] buffer = null;
    try {//  w w w. j  a  va 2 s  .c  o m
        RandomAccessFile raf = new RandomAccessFile(fileName, "r");
        buffer = new byte[(int) raf.length()];
        raf.readFully(buffer);
        raf.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    attributes.put("fileName", new File(fileName).getName());
    attributes.put("content", buffer);
    attributes.put("header", header);
    attributes.put("title", title);
    attributes.put("deleteFile", new Boolean(deleteFile));

    DirectJNI.getInstance().notifyRActionListeners(new RConsoleAction("PAGER", attributes));

}

From source file:edu.tsinghua.lumaqq.qq.Util.java

/**
 * MD5???10002432//from w ww . j  a v  a  2s.c  o  m
 * @param file RandomAccessFile
 * @return MD5
 */
public static byte[] getFileMD5(RandomAccessFile file) {
    try {
        file.seek(0);
        byte[] buf = (file.length() > QQ.QQ_MAX_FILE_MD5_LENGTH) ? new byte[QQ.QQ_MAX_FILE_MD5_LENGTH]
                : new byte[(int) file.length()];
        file.readFully(buf);
        return DigestUtils.md5(buf);
    } catch (IOException e) {
        return null;
    }
}

From source file:edu.sfsu.csc780.chathub.ui.ChannelActivity.java

private Uri saveAudio(String mFileName) {
    File returnAudioFile = null;//from  www.j  a v  a  2 s  .  c  o m

    try {
        returnAudioFile = createAudioFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (returnAudioFile == null) {
        Log.d(TAG, "Error creating media file");
        return null;
    }

    try {
        RandomAccessFile f = new RandomAccessFile(mFileName, "r");
        byte[] b = new byte[(int) f.length()];
        f.readFully(b);
        FileOutputStream fos = new FileOutputStream(returnAudioFile);
        fos.write(b);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }
    return Uri.fromFile(returnAudioFile);
}

From source file:org.exist.util.VirtualTempFile.java

/**
  * The method <code>getChunk</code>
  *// w  ww. ja  v a2  s  .c  o  m
  * @param offset a <code>long</code> value
  * @return a <code>byte[]</code> value
  * @exception IOException if an error occurs
  */
public byte[] getChunk(long offset) throws IOException {
    byte[] data = null;

    if (os != null) {
        close();
    }

    if (tempFile != null) {
        final RandomAccessFile raf = new RandomAccessFile(tempFile, "r");
        raf.seek(offset);
        long remaining = raf.length() - offset;
        if (remaining > maxChunkSize) {
            remaining = maxChunkSize;
        } else if (remaining < 0) {
            remaining = 0;
        }
        data = new byte[(int) remaining];
        raf.readFully(data);
        raf.close();
    } else if (tempBuffer != null) {
        long remaining = tempBuffer.length - offset;
        if (remaining > maxChunkSize) {
            remaining = maxChunkSize;
        } else if (remaining < 0) {
            remaining = 0;
        }
        data = new byte[(int) remaining];
        if (remaining > 0) {
            System.arraycopy(tempBuffer, (int) offset, data, 0, (int) remaining);
        }
    }

    return data;
}