Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java DataInputStream skipBytes() Method

In this tutorial, we will learn about the skipBytes() method of DataInputStream class in Java. This method is used to skip the given 'n' number of bytes of data from the given DataInputStream. It is a non-static method, available in the java.io package and it never throws an EOFException.

Syntax

This is the syntax of this method. It takes the number of bytes 'n' to be skipped as a parameter and returns the actual number of bytes skipped.

public final int skipBytes(int n) throws IOException  

Example: Skip Bytes in Java

In this example, we are implementing the skipBytes() method to skip the number of bytes from the given stream. Here, we can see we passed the six as a parameter to skip the 6 bytes, and then we are getting output after skipping the first 6 bytes.

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		FileInputStream inputStream  = new FileInputStream("E:\\studytonight\\file.txt"); 
		DataInputStream dataInputStream = new DataInputStream(inputStream); 
		dataInputStream.skipBytes(6);
		int count = inputStream.available();
		byte[] byte_arr = new byte[count]; 
		int bytes = dataInputStream.read(byte_arr); 
		for (byte b : byte_arr)
		{ 
			System.out.print((char)b); 
		} 
	}  
}


Studytonight

output.txt

Hello Studytonight

Example: Get The Skip Bytes in Java

Here, we are skipping the 2 bytes from the given stream so it will not read the first 2 bytes from the given stream and then it will print the next data. We can see the only 3 bytes of data from the byte array and the first 2 bytes are skipped.

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
        byte[] byte_arr = { 10, 20, 30, 40, 50 }; 
        ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(byte_arr); 
        DataInputStream dataInputStr = new DataInputStream(byteArrayInputStr); 
        dataInputStr.skipBytes(2);  
        while (dataInputStr.available() > 0) 
        { 
            System.out.println(dataInputStr.readByte()); 
        } 
	}  
}


30
40
50

Conclusion

In this tutorial, we learned about the skipBytes() method of DataInputStream class in Java which skips 'n' number of bytes of data from the given input stream and returns the exact number of bytes skipped.