Java IO Tutorial - Java RandomAccessFile.read(byte[] b, int off, int len)








Syntax

RandomAccessFile.read(byte[] b, int off, int len) has the following syntax.

public int read(byte[] b, int off, int len)  throws IOException

Example

In the following code shows how to use RandomAccessFile.read(byte[] b, int off, int len) method.

/*w w  w . ja  v a 2s . com*/

import java.io.*;

public class Main {

   public static void main(String[] args) {
      try {
         byte[] b1 = {1, 2, 3};
         byte[] b2 = {1, 2, 3, 4, 5, 6, 7, 8};
         
         RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

         // write something in the file
         raf.writeUTF("Hello World from java2s.com");

         // set the file pointer at 0 position
         raf.seek(0);

         // read 2 bytes, starting from 1
         System.out.println(raf.read(b1, 1, 2));

         // set the file pointer at 0 position
         raf.seek(0);

         // read 3 bytes, starting from 4rth
         System.out.println(raf.read(b2, 4, 3));
         raf.close();
      } catch (IOException ex) {
         ex.printStackTrace();
      }

   }
}