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.haulmont.cuba.core.sys.logging.LogArchiver.java

private static byte[] getTailBytes(File logFile) throws FileNotFoundException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    byte[] buf = null;
    int len;//from  w  w w  .j  a  va 2 s.com
    int size = 1024;
    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile(logFile, "r");
        long lengthFile = randomAccessFile.length();
        if (lengthFile >= LOG_TAIL_FOR_PACKING_SIZE) {
            randomAccessFile.seek(lengthFile - LOG_TAIL_FOR_PACKING_SIZE);
        }
        buf = new byte[size];
        while ((len = randomAccessFile.read(buf, 0, size)) != -1) {
            bos.write(buf, 0, len);
        }
        buf = bos.toByteArray();
    } catch (IOException e) {
        log.error("Unable to get tail for log file " + logFile.getName(), e);
    } finally {
        IOUtils.closeQuietly(bos);
    }
    return buf;
}

From source file:org.mycontroller.standalone.utils.McServerFileUtils.java

public static LogFile getLogUpdate(Long lastKnownPosition, Long lastNPosition) {
    if (lastNPosition != null && appLogFile.length() > lastNPosition) {
        lastKnownPosition = appLogFile.length() - lastNPosition;
    } else if (lastKnownPosition != null && appLogFile.length() <= lastKnownPosition) {
        return LogFile.builder().lastKnownPosition(lastKnownPosition).build();
    }//ww  w .  ja va  2s  .co m
    if (lastKnownPosition == null) {
        lastKnownPosition = 0L;
    }

    //Set maximum limit
    if ((appLogFile.length() - lastKnownPosition) > MAX_POSITION_LIMIT) {
        lastKnownPosition = appLogFile.length() - MAX_POSITION_LIMIT;
    }

    logBuilder.setLength(0);
    // Reading and writing file
    RandomAccessFile readFileAccess = null;
    try {
        readFileAccess = new RandomAccessFile(appLogFile, "r");
        readFileAccess.seek(lastKnownPosition);
        String log = null;
        while ((log = readFileAccess.readLine()) != null) {
            logBuilder.append(log).append("\n");
        }
        lastKnownPosition = readFileAccess.getFilePointer();
    } catch (FileNotFoundException ex) {
        _logger.error("Error,", ex);
    } catch (IOException ex) {
        _logger.error("Error,", ex);
    } finally {
        if (readFileAccess != null) {
            try {
                readFileAccess.close();
            } catch (IOException ex) {
                _logger.error("Error,", ex);
            }
        }
    }
    return LogFile.builder().lastKnownPosition(lastKnownPosition).data(logBuilder.toString()).build();
}

From source file:org.piwigo.remotesync.api.util.FileUtil.java

/**
 * chunkNumber start at 0/*w  w  w .  j  ava2  s .co m*/
 */
public static byte[] getFilePart(File file, int chunkSize, int chunkNumber) {
    RandomAccessFile randomAccessFile = null;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");
        int bytesSize = getChunkSize(file, chunkSize, chunkNumber);
        byte[] bytes = new byte[bytesSize];
        randomAccessFile.seek(chunkSize * chunkNumber);
        randomAccessFile.read(bytes, 0, bytesSize);
        return bytes;
    } catch (IOException e) {
        throw new IORuntimeException("Cannot get file part", e);
    } finally {
        IOUtils.closeQuietly(randomAccessFile);
    }
}

From source file:dk.netarkivet.common.utils.cdx.BinSearch.java

/** Skip to the next line after the given position by
 * reading a line.  Note that if the position is at the start
 * of a line, it will go to the next line.
 *
 * @param in A file to read from//from   w  w w  . j a  va 2s  . co  m
 * @param pos The position to start at.
 * @return A new position in the file.  The file's pointer (as given by
 * getFilePointer()) is updated to match.
 * @throws IOException If some I/O error occurs
 */
private static long skipToLine(RandomAccessFile in, long pos) throws IOException {
    in.seek(pos);
    in.readLine();
    return in.getFilePointer();
}

From source file:eu.delving.metadata.Hasher.java

public static String quickHash(File file) throws IOException {
    Hasher hasher = new Hasher();
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    byte[] chunk = new byte[QUICK_SAMPLE_SIZE];
    long length = raf.length() - chunk.length;
    long step = length / QUICK_SAMPLES;
    for (int walk = 0; walk < QUICK_SAMPLES; walk++) {
        raf.seek(step * walk);
        raf.readFully(chunk);/*from w  w  w  . ja  v a  2 s. c  om*/
        hasher.update(chunk, chunk.length);
    }
    raf.close();
    return hasher.getHashString().substring(4, 14);
}

From source file:WordList.java

public static void writeWords(String filename, String[] words) throws IOException {
    // Open the file for read/write access ("rw"). We only need to write,
    // but have to request read access as well
    RandomAccessFile f = new RandomAccessFile(filename, "rw");

    // This array will hold the positions of each word in the file
    long wordPositions[] = new long[words.length];

    // Reserve space at the start of the file for the wordPositions array
    // and the length of that array. 4 bytes for length plus 8 bytes for
    // each long value in the array.
    f.seek(4L + (8 * words.length));

    // Now, loop through the words and write them out to the file,
    // recording the start position of each word. Note that the
    // text is written in the UTF-8 encoding, which uses 1, 2, or 3 bytes
    // per character, so we can't assume that the string length equals
    // the string size on the disk. Also note that the writeUTF() method
    // records the length of the string so it can be read by readUTF().
    for (int i = 0; i < words.length; i++) {
        wordPositions[i] = f.getFilePointer(); // record file position
        f.writeUTF(words[i]); // write word
    }//from   w  w w  .j a va2 s .  c o m

    // Now go back to the beginning of the file and write the positions
    f.seek(0L); // Start at beginning
    f.writeInt(wordPositions.length); // Write array length
    for (int i = 0; i < wordPositions.length; i++)
        // Loop through array
        f.writeLong(wordPositions[i]); // Write array element
    f.close(); // Close the file when done.
}

From source file:dk.netarkivet.common.utils.cdx.BinSearch.java

/**
 * Return the index of the first line in the file to match 'find'. If the
 * lines in the file are roughly equal length, it reads
 * O(sqrt(n)) lines, where n is the distance from matchingline to the first
 * line./*from   ww  w.  j a v  a  2s  .co m*/
 *
 * @param in
 *            The file to search in
 * @param find
 *            The string to match against the first line
 * @param matchingline
 *            The index to start searching from.  This index must be at
 *            the start of a line that matches 'find'
 * @return The offset into the file of the first line matching 'find'.
 *         Guaranteed to be <= matchingline.
 * @throws IOException If the matchingLine < 0 or some I/O error occurs.
 */
private static long findFirstLine(RandomAccessFile in, String find, long matchingline) throws IOException {
    in.seek(matchingline);
    String line = in.readLine();
    if (line == null || compare(line, find) != 0) {
        final String msg = "Internal: Called findFirstLine without a " + "matching line in '" + in + "' byte "
                + matchingline;
        log.warn(msg);
        throw new ArgumentNotValid(msg);
    }
    // Skip backwards in quadratically increasing steps.
    int linelength = line.length();
    long offset = linelength;
    for (int i = 1; matchingline - offset > 0; i++, offset = i * i * linelength) {
        skipToLine(in, matchingline - offset);
        line = in.readLine();
        if (line == null || compare(line, find) != 0) {
            break;
        }
    }
    // Either found start-of-file or a non-matching line
    long pos;
    if (matchingline - offset <= 0) {
        pos = 0;
        in.seek(0);
    } else {
        pos = in.getFilePointer();
    }
    // Seek forwards line by line until the first matching line.
    // This takes no more than sqrt(n) steps since we know there is
    // a matching line that far away by the way we skipped to here.
    while ((line = in.readLine()) != null) {
        if (compare(line, find) == 0) {
            return pos;
        }
        pos = in.getFilePointer();
    }

    return -1;
}

From source file:org.syncany.tests.unit.util.TestFileUtil.java

public static void changeRandomPartOfBinaryFile(File file) throws IOException {
    if (file != null && !file.exists()) {
        throw new IOException("File does not exist: " + file);
    }//from  www.j  a va  2 s . c  o  m

    if (file.isDirectory()) {
        throw new IOException("Cannot change directory: " + file);
    }

    // Prepare: random bytes at random position
    Random randomEngine = new Random();

    int fileSize = (int) file.length();
    int maxChangeBytesLen = 20;
    int maxChangeBytesStartPos = (fileSize - maxChangeBytesLen - 1 >= 0) ? fileSize - maxChangeBytesLen - 1 : 0;

    int changeBytesStartPos = (maxChangeBytesStartPos > 0) ? randomEngine.nextInt(maxChangeBytesStartPos) : 0;
    int changeBytesLen = (fileSize - changeBytesStartPos < maxChangeBytesLen)
            ? fileSize - changeBytesStartPos - 1
            : maxChangeBytesLen;

    byte[] changeBytes = new byte[changeBytesLen];
    randomEngine.nextBytes(changeBytes);

    // Write to file
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

    randomAccessFile.seek(changeBytesStartPos);
    randomAccessFile.write(changeBytes);

    randomAccessFile.close();
}

From source file:net.sourceforge.doddle_owl.data.JpnWordNetDic.java

private static long getDataFp(long fp, RandomAccessFile indexFile) {
    try {//from  w w  w .  jav a2 s. c om
        indexFile.seek(fp);
        return Long.valueOf(indexFile.readLine());
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return -1;
}

From source file:com.geekandroid.sdk.pay.utils.Util.java

public static byte[] readFromFile(String fileName, int offset, int len) {
    if (fileName == null) {
        return null;
    }//  w w  w .  j a  va 2  s. c om

    File file = new File(fileName);
    if (!file.exists()) {
        Log.i(TAG, "readFromFile: file not found");
        return null;
    }

    if (len == -1) {
        len = (int) file.length();
    }

    Log.d(TAG, "readFromFile : offset = " + offset + " len = " + len + " offset + len = " + (offset + len));

    if (offset < 0) {
        Log.e(TAG, "readFromFile invalid offset:" + offset);
        return null;
    }
    if (len <= 0) {
        Log.e(TAG, "readFromFile invalid len:" + len);
        return null;
    }
    if (offset + len > (int) file.length()) {
        Log.e(TAG, "readFromFile invalid file len:" + file.length());
        return null;
    }

    byte[] b = null;
    try {
        RandomAccessFile in = new RandomAccessFile(fileName, "r");
        b = new byte[len]; // ??
        in.seek(offset);
        in.readFully(b);
        in.close();

    } catch (Exception e) {
        Log.e(TAG, "readFromFile : errMsg = " + e.getMessage());
        e.printStackTrace();
    }
    return b;
}