read File using RandomAccessFile - Android java.io

Android examples for java.io:RandomAccessFile

Description

read File using RandomAccessFile

Demo Code


//package com.java2s;
import java.io.*;

public class Main {
    public static byte[] readFile(String filename) throws IOException {
        return readFile(new File(filename));
    }/*from w  w  w . j  a  v  a2  s  .co m*/

    public static byte[] readFile(File file) throws IOException {
        // Open file
        RandomAccessFile f = new RandomAccessFile(file, "r");
        try {
            // Get and check length
            long longlength = f.length();
            int length = (int) longlength;
            if (length != longlength)
                throw new IOException("File size >= 2 GB");
            // Read file and return data
            byte[] data = new byte[length];
            f.readFully(data);
            return data;
        } finally {
            f.close();
        }
    }
}

Related Tutorials