Write a java program to Read text from file from a specified index or skipping byte using FileInputStream


This Java program demonstrates how to skip bytes and read the content of a file. The program performs the following steps:

  • It creates an instance of the File class with the name of the file to be read as an argument.
  • It creates a FileInputStream object to read the contents of the file.
  • It uses the skip() method of the FileInputStream class to skip the first 5 bytes of the file.
  • It reads the remaining contents of the file using the read() method of the FileInputStream class.
  • It prints the contents of the file on the console.

If any exception is thrown during the execution of the program, it is caught and an appropriate error message is displayed. Overall, the program demonstrates how to skip bytes in a file and read its contents using FileInputStream in Java.

Source Code

import java.io.*;
public class Skipping_Byte
{
	public static void main(String[] args)
	{    
		File file = new File("file.txt");
		try
		{
			FileInputStream fi = new FileInputStream(file);
			int ch;
 
			System.out.print("File's Content after 5 bytes is : ");
 
			//skipping 5 bytes to read the file
			fi.skip(5);
 
			while ((ch = fi.read()) != -1)
			{
				System.out.print((char) ch);
			}
		}
		catch (FileNotFoundException f) {
			System.out.println("FileNotFoundException : " + f.toString());
		}
		catch (IOException i)
		{
			System.out.println("IOException : " + i.toString());
		}
		catch (Exception e) {
			System.out.println("Exception: " + e.toString());
		}
	}
}

Output

File's Content after 5 bytes is : is Java Programs