Example usage for java.io RandomAccessFile length

List of usage examples for java.io RandomAccessFile length

Introduction

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

Prototype

public native long length() throws IOException;

Source Link

Document

Returns the length of this file.

Usage

From source file:org.apache.hadoop.hdfs.server.namenode.FSImageUtil.java

public static FileSummary loadSummary(RandomAccessFile file) throws IOException {
    final int FILE_LENGTH_FIELD_SIZE = 4;
    long fileLength = file.length();
    file.seek(fileLength - FILE_LENGTH_FIELD_SIZE);
    int summaryLength = file.readInt();

    if (summaryLength <= 0) {
        throw new IOException("Negative length of the file");
    }//from w  w  w  .  j  av  a 2 s.  co m
    file.seek(fileLength - FILE_LENGTH_FIELD_SIZE - summaryLength);

    byte[] summaryBytes = new byte[summaryLength];
    file.readFully(summaryBytes);

    FileSummary summary = FileSummary.parseDelimitedFrom(new ByteArrayInputStream(summaryBytes));
    if (summary.getOndiskVersion() != FILE_VERSION) {
        throw new IOException("Unsupported file version " + summary.getOndiskVersion());
    }

    if (!NameNodeLayoutVersion.supports(Feature.PROTOBUF_FORMAT, summary.getLayoutVersion())) {
        throw new IOException("Unsupported layout version " + summary.getLayoutVersion());
    }
    return summary;
}

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;//  w  w w  .  j  av a 2s.c o  m
    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: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);//w  w w . jav a 2s . co m
        raf.readFully(chunk);
        hasher.update(chunk, chunk.length);
    }
    raf.close();
    return hasher.getHashString().substring(4, 14);
}

From source file:com.shopgun.android.sdk.utils.ExternalClientIdStore.java

public static String getCid(ShopGun sgn) {

    // First try SharedPrefs
    String cid = sgn.getSettings().getClientId();
    if (cid != null) {
        return cid;
    }/*from  w w w.  ja  v  a  2  s. c o m*/

    // Then try external storage
    File cidFile = getCidFile(sgn.getContext());
    if (cidFile == null) {
        return null;
    }

    RandomAccessFile f = null;
    try {
        f = new RandomAccessFile(cidFile, "r");
        // Get and check length
        long longlength = f.length();
        int length = (int) longlength;
        if (length != longlength)
            return null;
        // Read file and return data
        byte[] data = new byte[length];
        f.readFully(data);
        return new String(data);
    } catch (Exception e) {
        // Ignore
    } finally {
        try {
            f.close();
        } catch (Exception e) {
            // Ignore
        }

        // Cleanup the cid file, we won't need it any more
        deleteCidFile(sgn.getContext());
    }

    return null;
}

From source file:org.fusesource.meshkeeper.util.internal.FileSupport.java

static public byte[] read(File file, long pos, int length) throws IOException {
    RandomAccessFile is = new RandomAccessFile(file, "r");
    try {//from   w w  w . j a  va  2s  .  co m
        long remaining = is.length() - pos;
        if (remaining < 0) {
            remaining = 0;
        }
        byte rc[] = new byte[(int) Math.min(remaining, length)];
        if (rc.length == 0) {
            return rc;
        }
        is.seek(pos);
        is.readFully(rc);
        return rc;
    } finally {
        is.close();
    }
}

From source file:Main.java

public static byte[] getAsBinary(String key) {
    RandomAccessFile RAFile = null;
    boolean removeFile = false;
    try {/*w  w  w  .  j a va2  s .c om*/
        File file = new File(cacheDir, key);
        if (!file.exists())
            return null;
        RAFile = new RandomAccessFile(file, "r");
        byte[] byteArray = new byte[(int) RAFile.length()];
        RAFile.read(byteArray);
        return byteArray;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (RAFile != null) {
            try {
                RAFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

From source file:com.parse.ParseKeyValueCache.java

static String loadFromKeyValueCache(final String key, final long maxAgeMilliseconds) {
    synchronized (MUTEX_IO) {
        File file = getKeyValueCacheFile(key);
        if (file == null) {
            return null;
        }//from  w w w.j  a  v  a2s  .  c o m

        Date now = new Date();
        long oldestAcceptableAge = Math.max(0, now.getTime() - maxAgeMilliseconds);
        if (getKeyValueCacheAge(file) < oldestAcceptableAge) {
            return null;
        }

        // Update mtime to make the LRU work
        file.setLastModified(now.getTime());

        try {
            RandomAccessFile f = new RandomAccessFile(file, "r");
            byte[] bytes = new byte[(int) f.length()];
            f.readFully(bytes);
            f.close();
            return new String(bytes, "UTF-8");
        } catch (IOException e) {
            PLog.e(TAG, "error reading from cache", e);
            return null;
        }
    }
}

From source file:org.stem.db.FatFileAllocator.java

public static void allocateFile(String filePath, long sizeInMB, boolean mark) throws IOException {
    long started = System.currentTimeMillis();

    Closer closer = Closer.create();// w  w w.ja v  a 2s . c  o  m
    try {
        File file = new File(filePath);
        if (file.exists())
            throw new IOException(String.format("File already exists: %s", filePath));

        RandomAccessFile rw = closer.register(new RandomAccessFile(file, "rw"));
        rw.setLength(sizeInMB * 1024 * 1024);
        if (mark) {
            rw.seek(0);
            rw.writeByte(FatFile.MARKER_BLANK);
            rw.seek(rw.length() - 1);
            rw.writeByte(FatFile.MARKER_BLANK);
        }
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
        logger.debug("{} was allocated in {} ms", filePath, System.currentTimeMillis() - started);
    }
}

From source file:com.aoyetech.fee.commons.utils.FileUtils.java

public static String getFileContent(final File tFile)
        throws IOException, FileNotFoundException, UnsupportedEncodingException {
    if (!tFile.isFile()) {
        throw new IOException("?");
    }//from  www .  j  a  va 2  s.  c o  m
    final RandomAccessFile file = new RandomAccessFile(tFile, "r");
    final long fileSize = file.length();
    final byte[] bytes = new byte[(int) fileSize];
    long readLength = 0L;
    while (readLength < fileSize) {
        final int onceLength = file.read(bytes, (int) readLength, (int) (fileSize - readLength));
        if (onceLength > 0) {
            readLength += onceLength;
        } else {
            break;
        }
    }

    IOUtils.closeQuietly(file);
    return new String(bytes, Constants.ENCODE);
}

From source file:fm.last.commons.io.LastFileUtils.java

/**
 * Reads the last bytes from the end of the passed file as a String.
 * /*from ww  w . j  a v  a2 s .  c o m*/
 * @param file File to read from.
 * @param bytes Number of bytes from end of file to read.
 * @return The end content of the file as a String.
 * @throws IOException If the file could not be opened or read.
 */
public static String tail(File file, long bytes) throws IOException {
    RandomAccessFile raFile = null;
    StringBuffer tail = new StringBuffer();
    try {
        raFile = new RandomAccessFile(file, "r");
        long length = raFile.length();
        if (bytes >= length) {
            return FileUtils.readFileToString(file);
        } else {
            raFile.seek(length - bytes);
            tail = new StringBuffer((int) bytes);
            String line = raFile.readLine();
            while (line != null) {
                tail.append(line);
                line = raFile.readLine();
                if (line != null) { // there is another line coming, so add line break
                    tail.append("\n");
                }
            }
        }
    } finally {
        LastIoUtils.closeQuietly(raFile);
    }
    return tail.toString();
}