Write a Java program that reads a file and displays the file on the screen, with a line number before each line.

//Program to print the contents of the file along with line number
import java.util.*;
import java.io.*;
class Rfile
{
            public static void main(String args[])throws IOException
            {
                        int j=1;
                        char ch;
                        Scanner scr=new Scanner(System.in);
                        System.out.print(“nEnter File name: “);
                        String str=scr.next();
                        FileInputStream f=new FileInputStream(str);
                        System.out.println(“nContents of the file are”);
                        int n=f.available();
                        System.out.print(j+”: “);
                        for(int i=0;i<n;i++)
                        {
                                    ch=(char)f.read();
                                    System.out.print(ch);
                                    if(ch==’n’)
                                    {
                                                System.out.print(++j+”: “);
                                               
                                    }
                                               
                        }
            }
}
Output:
Enter File name: raj.txt
Contents of the file are :
1: kotireddy
2: Santhosh

3: Vamsi

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Enable Notifications OK No thanks