1. 程式人生 > >How to read a file bytes from a offset

How to read a file bytes from a offset

example:

public class IOUtil {

    public static byte[] readFile(String file) throws IOException {
        return readFile(new File(file));
    }

    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(); } } }
public static byte[] toByteArray(File file, long start, long count) {
      long length = file.length();
      if (start >= length) return new
byte[0]; count = Math.min(count, length - start); byte[] array = new byte[count]; InputStream in = new FileInputStream(file); in.skip(start); long offset = 0; while (offset < count) { int tmp = in.read(array, offset, (length - offset)); offset += tmp; } in.close(); return array; }
from:
int A constant holding the maximum value an int can have, 231-1.

意思是,(2的31次方)-1
也就是2,147,483,648-1=2,147,483,647

超過 2GB 的檔案無法使用 offset! 可以改用

public long skip(long byteCount) throws IOException {
    return Streams.skipByReading(this, byteCount);
}
      FileInputStream fis = null;
      int i=0;
      char c;
            
      try{
         // create new file input stream
         fis = new FileInputStream("C://test.txt");
         
         // skip bytes from file input stream
         fis.skip(4);
         
         // read bytes from this stream
         i = fis.read();
         
         // converts integer to character
         c = (char)i;
         
         // prints
         System.out.print("Character read: "+c);
   
      }catch(Exception ex){
         // if any error occurs
         ex.printStackTrace();
      }finally{
         
         // releases all system resources from the streams
         if(fis!=null)
            fis.close();
      }