Java.io.RandomAccessFile.read() Method

Advertisements


Description

The java.io.RandomAccessFile.read(byte[] b) method reads up to b.length 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)

Parameters

  • b -- the buffer into which the data is 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 this 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.

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 the first 8 bytes and print the number of bytes read
         System.out.println("" + raf.read(b1));

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

         // read the first 8 bytes and print the number of bytes read
         System.out.println("" + raf.read(b2));
      } 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:

3
8



Advertisements
Advertisements