Example usage for java.io RandomAccessFile read

List of usage examples for java.io RandomAccessFile read

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this file into an array of bytes.

Usage

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 w w  w  .ja  v a  2 s  .com

    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:com.guodong.sun.guodong.uitls.CacheUtil.java

/**
 * ? byte ?/*from   w  ww .  ja  va 2s . c  om*/
 *
 * @param key
 * @return byte ?
 */
public byte[] getAsBinary(String key) {
    RandomAccessFile raFile = null;
    boolean removeFile = false;
    try {
        File file = mCache.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:jsave.Utils.java

static Matrix read_array(RandomAccessFile raf, int typecode, HashMap array_desc) throws Exception {

    //TODO : To be refactored to take into account typecode
    //        if (typecode == 1 || typecode == 3 || typecode == 4 ||
    //                typecode == 5 || typecode == 6 || typecode == 9 || typecode == 13 ||
    //                typecode == 14 || typecode == 15) {
    //            if (typecode == 1) {
    //                int nbBytes = read_int32(raf);
    //                if (nbBytes != (int) array_desc.get("nbytes")) {
    //                    throw new Exception("Error occurred while reading byte array");
    //                }
    //            }
    //            // read as numpy array
    //            byte[] data = new byte[(int) array_desc.get("nbytes")];
    //            raf.read(data);
    //            Array ok =  fromString(data, DTYPE_DICT.get(typecode));
    ///* w  ww.  j a  va  2 s. c o  m*/
    //        } else if (typecode == 2 || typecode == 12) {
    //            // JC old version
    //            byte[] data = new byte[(int) array_desc.get("nbytes")];
    //            raf.read(data);
    //            ByteArrayInputStream bas = new ByteArrayInputStream(data);
    //            DataInputStream ds = new DataInputStream(bas);
    //            float[] fArr = new float[data.length / 4];  // 4 bytes per float
    //            for (int i = 0; i < fArr.length; i++) {
    //                fArr[i] = ds.readFloat();
    //            }
    //        }
    byte[] data = new byte[(int) array_desc.get("nbytes")];
    raf.read(data);
    ByteArrayInputStream bas = new ByteArrayInputStream(data);
    DataInputStream ds = new DataInputStream(bas);
    float[] fArr = new float[data.length / 4]; // 4 bytes per float
    for (int i = 0; i < fArr.length; i++) {
        fArr[i] = ds.readFloat();
    }

    Matrix cube;
    int nbDims = (int) array_desc.get("ndims");

    int[] dims = new int[nbDims];
    int[] tmpDims = (int[]) array_desc.get("dims");

    // Filtering useless '1' value in dimension tab
    int j = 0;
    for (int i = 0; i < tmpDims.length; i++) {
        if (tmpDims[i] != 1) {
            dims[j] = tmpDims[i];
            j++;
        }
    }
    reverseArray(dims);

    int xDim = (dims.length >= 1) ? dims[0] : 1;
    int yDim = (dims.length >= 2) ? dims[1] : 1;
    int zDim = (dims.length == 3) ? dims[2] : 1;
    cube = new Matrix(xDim, yDim, zDim); // 480, 120, 69 ==> 3974400

    int indfArr = 0;
    for (int d2 = 0; d2 < zDim; d2++) { // 69 plans
        for (int d0 = 0; d0 < xDim; d0++) { // 480 lignes
            for (int d1 = 0; d1 < yDim; d1++) { // 120 colonnes
                cube.setCubeValue(d0, d1, d2, fArr[indfArr]);
                indfArr++;
            }
        }
    }

    align_32(raf);

    return cube;
}

From source file:com.android.volley.cache.ACache.java

/**
 * ? byte ?//from w w  w.j  a va  2  s .c  om
 * 
 * @param key
 * @return byte ?
 */
//   public byte[] getAsBinary(String key) {
public BinaryShell getAsBinary(String key) {
    RandomAccessFile RAFile = null;
    //      boolean removeFile = false;
    try {
        File file = mCache.get(key);
        if (!file.exists())
            return null;
        RAFile = new RandomAccessFile(file, "r");
        byte[] byteArray = new byte[(int) RAFile.length()];
        RAFile.read(byteArray);

        BinaryShell shell = new BinaryShell();
        shell.content = Utils.clearDateInfo(byteArray);
        if (!Utils.isDue(byteArray)) {
            shell.outOfDate = false;
        } else {
            shell.outOfDate = true;
        }
        //         if (!Utils.isDue(byteArray)) {
        //            return Utils.clearDateInfo(byteArray);
        //         } else {
        //            removeFile = true;
        //            return null;
        //         }
        return shell;
    } 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.mhisoft.wallet.service.AttachmentService.java

private ReadContentVO readCipherParameter(RandomAccessFile fileIn, long pos)
        throws IOException, NoSuchAlgorithmException {
    ReadContentVO ret = new ReadContentVO();
    ret.pos = pos;/*from w  w w  . jav a 2 s .  c  o  m*/

    /*#3: ciperParameters size 4 bytes*/
    int cipherParametersLength = fileIn.readInt();
    ret.pos += 4;
    //logger.fine("read cipherParametersLength:" + cipherParametersLength);

    /*#4: cipherParameters body*/
    byte[] _byteCiper = new byte[cipherParametersLength];
    int readBytes = fileIn.read(_byteCiper);
    if (readBytes != cipherParametersLength)
        throw new RuntimeException("read " + readBytes + " bytes only, expected to read:" + _byteCiper);
    ret.pos += _byteCiper.length;

    ret.algorithmParameters = AlgorithmParameters.getInstance(PBEEncryptor.ALGORITHM);
    ret.algorithmParameters.init(_byteCiper);

    return ret;

}

From source file:FileBaseDataMap.java

/**
 * ?????.<br>/*from  w  ww . ja va2s  .c om*/
 * ????null?.<br>
 *
 * @param
 * @return 
 * @throws
 */
public List getAllOneFileInKeys() {

    List keys = null;
    byte[] datas = null;
    StringBuffer keysBuf = null;

    try {
        if (this.nowIterationFileIndex < this.dataFileList.length) {

            keys = new ArrayList();
            datas = new byte[new Long(this.dataFileList[this.nowIterationFileIndex].length()).intValue()];

            RandomAccessFile raf = new RandomAccessFile(this.dataFileList[this.nowIterationFileIndex], "rwd");

            raf.seek(0);
            int readLen = -1;
            readLen = raf.read(datas);

            if (readLen > 0) {

                int loop = readLen / lineDataSize;

                for (int loopIdx = 0; loopIdx < loop; loopIdx++) {

                    int assist = (lineDataSize * loopIdx);
                    keysBuf = new StringBuffer();

                    int idx = 0;

                    while (true) {

                        if (datas[assist + idx] != 38) {
                            keysBuf.append(new String(datas, assist + idx, 1));
                        } else {
                            break;
                        }
                        idx++;
                    }
                    keys.add(keysBuf.toString());
                }
            }
        }
        this.nowIterationFileIndex++;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return keys;
}

From source file:org.eclipse.ice.item.utilities.moose.MOOSEFileHandler.java

/**
 * This operations loads a MOOSE GetPot file at the specified path and
 * returns a fully-configured set of ICE TreeComposites.
 * /*from   w  ww  .jav a2 s  .  co m*/
 * @param filePath
 *            The file path from which the MOOSE blocks written in GetPot
 *            should be read. If the path is null or empty, the operation
 *            returns without doing any work.
 * @return The MOOSE input file specification as read from the GetPot input
 *         and stored in TreeComposites. Each TreeComposite contains both
 *         parameters and exemplar children. Any parameters in a
 *         TreeComposite are contained in a DataComponent. The id of the
 *         data component is 1.
 */
public ArrayList<TreeComposite> loadFromGetPot(String filePath) {

    // Local Declarations
    ArrayList<TreeComposite> trees = new ArrayList<TreeComposite>();
    byte[] fileByteArray = null;
    String mooseFileString = null, potLine = null;

    // Quit if the path is boned
    if (filePath == null || filePath.isEmpty()) {
        return null;
    }

    // Post some debug info
    if (debugFlag) {
        logger.info("MOOSEFileHandler Message: " + "Attempting to loading GetPot file " + filePath);
    }

    // Load the GetPot file
    try {
        RandomAccessFile mooseFile = new RandomAccessFile(filePath, "r");
        // Put it into a byte array
        fileByteArray = new byte[(int) mooseFile.length()];
        mooseFile.read(fileByteArray);
        // And then a string
        mooseFileString = new String(fileByteArray);
        // Close the file
        mooseFile.close();
        // Post some more debug info
        if (debugFlag) {
            logger.info("MOOSEFileHandler Message: File loaded.");
        }
    } catch (IOException e) {
        // Complain if the file is not found
        System.err.println("MOOSEFileHandler Message: " + "Unable to load GetPot file!");
        logger.error(getClass().getName() + " Exception!", e);
    }

    // Check the string before proceeding
    if (mooseFileString != null && !mooseFileString.isEmpty()) {
        // Create an array list from the string
        ArrayList<String> potLines = new ArrayList<String>(Arrays.asList(mooseFileString.split("\n")));

        // Remove (non-parameter) commented lines and white space
        String trimmedPotLine = "";
        for (int i = 0; i < potLines.size(); i++) {

            trimmedPotLine = potLines.get(i).trim();

            if (trimmedPotLine.startsWith("#") && !trimmedPotLine.contains("=") && !trimmedPotLine.contains("[")
                    && !trimmedPotLine.contains("]")) {
                // Lines that start with "#" but have no "=" are comments
                // that aren't parameters and should be removed
                potLines.remove(i);
                // Update "i" so that we read correctly
                --i;
            } else if (potLines.get(i).isEmpty()) {
                // Remove empty lines
                potLines.remove(i);
                // Update "i" so that we read correctly
                --i;
            } else {
                // This is a rare scenario to check for, but it's possible
                // (and has happened at least once) where a line is just a
                // comment (starts with "#") AND includes a "=" in the text
                // of the comment
                if (trimmedPotLine.startsWith("#") && trimmedPotLine.contains("=")) {
                    String[] splitTrimmedPotLine = trimmedPotLine.split("\\s+");
                    if (splitTrimmedPotLine.length > 4) {
                        // Skip this line, it's a comment that's been
                        // mistaken as a parameter
                        potLines.remove(i);
                        --i;
                        continue;
                    }
                }

                // Otherwise, the normal behavior is that the line should be
                // trimmed and be considered a real parameter
                potLines.set(i, potLines.get(i).trim());
            }
        }

        // Read all of the lines again, create blocks and load them.
        int counter = 0, endCounter = 1;
        while (counter < potLines.size()) {
            // Get the line and shift the counters
            potLine = potLines.get(counter);
            ++counter;

            // The start of a full block is a line with the name in brackets
            // and without the "./" sequence.
            if (potLine.contains("[") && potLine.contains("]")) {
                // Go to the next line
                potLine = potLines.get(endCounter);

                // Loop over the block and find the end
                while (!potLine.contains("[]")) {
                    // Update the line and the counter
                    potLine = potLines.get(endCounter);
                    ++endCounter;
                }
                // Create a new block
                Block block = new Block();
                ArrayList<String> blockLines = null;
                if (endCounter >= counter - 1) {
                    blockLines = new ArrayList<String>(potLines.subList(counter - 1, endCounter));
                }
                if (blockLines != null && !blockLines.isEmpty()) {
                    StringBuilder stringBuilder = new StringBuilder(blockLines.get(0));
                    blockLines.set(0, stringBuilder.toString());
                    block.fromGetPot(blockLines);
                    // Add the block to the list
                    trees.add(block.toTreeComposite());
                    // Update the counter to point to the last read line
                    counter = endCounter;
                }

                // Print some debug information
                if (debugFlag) {
                    logger.info("\nMOOSEFileHandler Message: " + "Block output read from GetPot file "
                            + filePath + " follows.");
                    // Dump each line of the newly created block
                    for (String line : blockLines) {
                        logger.info(line);
                    }
                }

            }
        }
    } else if (debugFlag) {
        System.err.println(
                "MOOSEFileHandler Message: " + "String loaded from " + filePath + " is null or empty.");
    }

    return trees;
}

From source file:org.hrva.capture.LogTail.java

/**
 * Tail the given file if the size has changed and return a temp filename.
 *
 * <p>This returns a temp filename if the log being tailed has changed.
 * </p>//www  .  j a  va 2  s  .  c o  m
 * 
 * <p>The supplied target filename is -- actually -- a format string.
 * The available value, <<tt>{0}</tt> is the sequence number
 * that's saved in the history cache.</p>
 *
 * @param source The log filename to tail
 * @param target A temporary filename into which to save the tail piece.
 * @return temp filename, if the file size changed; otherwise null
 * @throws FileNotFoundException
 * @throws IOException
 */
public String tail(String source, String target) throws FileNotFoundException, IOException {
    // The resulting file name (or null if the log did not grow).
    String temp_name = null;

    // Open our last-time-we-looked file.
    String cache_file_name = global.getProperty("logtail.tail_status_filename", "logtail.history");
    String limit_str = global.getProperty("logtail.file_size_limit", "1m"); // 1 * 1024 * 1024;
    int limit;
    if (limit_str.endsWith("m") || limit_str.endsWith("M")) {
        limit = 1024 * 1024 * Integer.parseInt(limit_str.substring(0, limit_str.length() - 1));
    } else if (limit_str.endsWith("k") || limit_str.endsWith("K")) {
        limit = 1024 * Integer.parseInt(limit_str.substring(0, limit_str.length() - 1));
    } else {
        limit = Integer.parseInt(limit_str);
    }

    Properties state = get_state(cache_file_name);

    // Find the previous size and sequence number
    String prev_size_str = state.getProperty("size." + source, "0");
    long prev_size = Long.parseLong(prev_size_str);
    String seq_str = state.getProperty("seq." + source, "0");
    long sequence = Long.parseLong(seq_str);

    Object[] details = { source, target, seq_str, prev_size_str };
    logger.info(MessageFormat.format("Tailing {0} to {1}", details));
    logger.info(MessageFormat.format("Count {2}, Bytes {3}", details));
    sequence += 1;

    // Attempt to seek to the previous position
    long position = 0;
    File log_to_tail = new File(source);
    RandomAccessFile rdr = new RandomAccessFile(log_to_tail, "r");
    try {
        long current_size = rdr.length();
        if (current_size == prev_size) {
            // Same size.  Nothing more to do here.
            position = current_size;
        } else {
            // Changed size.  Either grew or was truncated.
            if (rdr.length() < prev_size) {
                // Got truncated.  Read from beginning.
                sequence = 0;
                prev_size = 0;
            } else {
                // Got bigger.  Read from where we left off.
                rdr.seek(prev_size);
            }
            // Read to EOF or the limit.  
            // No reason to get greedy.
            int read_size;
            if (current_size - prev_size > limit) {
                read_size = limit;
                rdr.seek(current_size - limit);
            } else {
                read_size = (int) (current_size - prev_size);
            }
            byte[] buffer = new byte[read_size];
            rdr.read(buffer);
            position = rdr.getFilePointer();

            // Write temp file
            Object[] args = { sequence };
            temp_name = MessageFormat.format(target, args);

            File extract = new File(temp_name);
            OutputStream wtr = new FileOutputStream(extract);
            wtr.write(buffer);
        }
    } finally {
        rdr.close();
    }

    // Update our private last-time-we-looked file.
    state.setProperty("size." + source, String.valueOf(position));
    state.setProperty("seq." + source, String.valueOf(sequence));
    save_state(cache_file_name, state);

    Object[] details2 = { source, target, seq_str, prev_size_str, String.valueOf(sequence),
            String.valueOf(position) };
    logger.info(MessageFormat.format("Count {4}, Bytes {5}", details2));

    return temp_name;
}

From source file:adept.io.Reader.java

/**
 * Reads specified file into a byte array.
 *
 * @param path the path// ww w.j ava  2s.c  o m
 * @return the byte[]
 */
public byte[] readFileIntoByteArray(String path) {
    try {
        RandomAccessFile f = new RandomAccessFile(path, "r");
        byte[] b = new byte[(int) f.length()];
        f.read(b);
        f.close();
        return b;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.googlecode.psiprobe.Utils.java

public static void sendFile(HttpServletRequest request, HttpServletResponse response, File file)
        throws IOException {
    OutputStream out = response.getOutputStream();
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    try {/* ww  w . j  a va 2s.  c  o  m*/
        long fileSize = raf.length();
        long rangeStart = 0;
        long rangeFinish = fileSize - 1;

        // accept attempts to resume download (if any)
        String range = request.getHeader("Range");
        if (range != null && range.startsWith("bytes=")) {
            String pureRange = range.replaceAll("bytes=", "");
            int rangeSep = pureRange.indexOf("-");

            try {
                rangeStart = Long.parseLong(pureRange.substring(0, rangeSep));
                if (rangeStart > fileSize || rangeStart < 0) {
                    rangeStart = 0;
                }
            } catch (NumberFormatException e) {
                // ignore the exception, keep rangeStart unchanged
            }

            if (rangeSep < pureRange.length() - 1) {
                try {
                    rangeFinish = Long.parseLong(pureRange.substring(rangeSep + 1));
                    if (rangeFinish < 0 || rangeFinish >= fileSize) {
                        rangeFinish = fileSize - 1;
                    }
                } catch (NumberFormatException e) {
                    // ignore the exception
                }
            }
        }

        // set some headers
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Content-Length", Long.toString(rangeFinish - rangeStart + 1));
        response.setHeader("Content-Range", "bytes " + rangeStart + "-" + rangeFinish + "/" + fileSize);

        // seek to the requested offset
        raf.seek(rangeStart);

        // send the file
        byte[] buffer = new byte[4096];

        long len;
        int totalRead = 0;
        boolean nomore = false;
        while (true) {
            len = raf.read(buffer);
            if (len > 0 && totalRead + len > rangeFinish - rangeStart + 1) {
                // read more then required?
                // adjust the length
                len = rangeFinish - rangeStart + 1 - totalRead;
                nomore = true;
            }

            if (len > 0) {
                out.write(buffer, 0, (int) len);
                totalRead += len;
                if (nomore) {
                    break;
                }
            } else {
                break;
            }
        }
    } finally {
        raf.close();
    }
}