Java.io.RandomAccessFile.skipBytes() Method



Description

The java.io.RandomAccessFile.skipBytes(int n) method Attempts to skip over n bytes of input discarding the skipped bytes. This method may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility. This method never throws an EOFException. The actual number of bytes skipped is returned. If n is negative, no bytes are skipped.

Declaration

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

public int skipBytes(int n)

Parameters

n − The number of bytes to be skipped.

Return Value

This method returns the actual number of bytes skipped.

Exception

IOException − If an I/O error occurs.

Example

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

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {
   
      try {
         // 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);

         // print the string
         System.out.println("" + raf.readUTF());

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

         // attempt to skip 10 bytes and print the number of bytes skipped
         System.out.println("" + raf.skipBytes(10));

         // print what is left after skipping
         System.out.println("" + raf.readLine());

         // set the file pointer to position 8
         raf.seek(8);

         // attempt to skip 10 more bytes and print the number of bytes skipped
         System.out.println("" + raf.skipBytes(10));
         
      } 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 −

Hello World
10
rld
5
java_io_randomaccessfile.htm
Advertisements