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:

http://stackoverflow.com/questions/18811608/how-to-read-fixed-number-of-bytes-from-a-file-in-a-loop-in-java


read 副程式用的 offset 參數只能到 int, int ranger:
https://developer.android.com/reference/java/lang/Integer.html

int MAX_VALUEA 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);
}

http://www.tutorialspoint.com/java/io/fileinputstream_skip.htm
      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();
      }

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *