Saturday, November 15, 2025
HomeLanguagesJavaJava Program to Read Text From File From a Specified Index

Java Program to Read Text From File From a Specified Index

In a file system, without reading the previous text we cannot directly access the specific index. Thus, Reading text from a file from the specific index is achieved by skipping all the previous characters of a specified index. To read text from an index n, we need to skip (n-1) bytes. Here, we will use  FileInputStream class to read text from the file.

long skip(long n): Skips over and discards n bytes of data from the input stream.

Syntax:

public long skip(long n) throws IOException

Parameters: n — the number of bytes to be skipped.

Returns: The actual number of bytes skipped.

Throws: IOException

Java




// Java program to read text from file from a specified
// index
  
import java.io.FileInputStream;
  
public class GFG {
  
    public static void main(String args[])
    {
  
        try {
            
            // attach the file to FileInputStream
            FileInputStream fin = new FileInputStream(
                "C:\\Users\\ASPIRE\\Desktop\\java folder\\Demo.txt");
  
            int i = 0;
            
            // discards 7 bytes of data from the input
            // stream.
            fin.skip(7);
            
            // read from the file
            System.out.print("Printing text from index 8: ");
            
            while ((i = fin.read()) != -1) {
  
                System.out.print((char)i);
            }
  
            fin.close();
        }
        catch (Exception e) {
  
            System.out.println(e);
        }
    }
}


   

Demo.txt file:

Output:

RELATED ARTICLES

Most Popular

Dominic
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11985 POSTS0 COMMENTS
Shaida Kate Naidoo
6890 POSTS0 COMMENTS
Ted Musemwa
7143 POSTS0 COMMENTS
Thapelo Manthata
6838 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS