Java.io.RandomAccessFile.read() Method



Description

The java.io.RandomAccessFile.read((byte[] b,int off,int len) method reads up to len bytes of data from this file into an array of bytes.

Declaration

Following is the declaration for java.io.RandomAccessFile.read() method.

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

Parameters

  • b − The buffer into which the data is read.

  • off − The start offset in array b at which the data is written.

  • len − The maximum number of bytes read.

Return Value

This method returns the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.

Exception

  • IOException − If an I/O error occurs.Not thrown if end-of-file has been reached.

  • NullPointerException − If b is null.

  • IndexOutOfBoundsException − If off is negative, len is negative, or len is greater than b.length - off.

Example

The following example shows the usage of java.io.RandomAccessFile.read() method.

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {

      try {
         byte[] b1 = {1, 2, 3};
         byte[] b2 = {1, 2, 3, 4, 5, 6, 7, 8};

         // create a new RandomAccessFile with filename test
         RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

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

         // 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));         
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program −

ABCDE  

Let us compile and run the above program, this will produce the following result −

2
3
java_io_randomaccessfile.htm
Advertisements