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

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

Aim:

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

Algorithm:

  1. import java package
  2. Create class Linenum
  3. Create main function
  4. public static void main( String[] args)throws IOException
    1. FileInputStream fil;
    2. LineNumberInputStream line;
    3. int i;
  5. Create try block
    1. fil = new FileInputStream(args[0]);
    2. line = new LineNumberInputStream( file );
  6. Catch( FileNotFoundException e )
  7. Print No such file found
  8. Inside do
  9. read line i = line.read();
  10. Use if condition
    1. if( i == ‘n’)
      1. System.out.print(line.getLineNumber()+” “);
    2. Else: System.out.print((char)i);
  11. Use while loop:
    1. while(i!=-1);
      1. fil.close();
      2. line.close();

Source Code:

import java.io.*;
class linenum
{
public static void main(String[] args)throws IOException
{
FileInputStream fil;
LineNumberInputStream line;
int i;
try
{
fil=new FileInputStream(args[0]);
line=new LineNumberInputStream(fil);
}
catch(FileNotFoundException e)
{
System.out.println("No such file found");
return;
}
do
{
i=line.read();
if(i=='n')
{
System.out.println();
System.out.print(line.getLineNumber()+" ");
}
else
System.out.print((char)i);
}while(i!=-1);
fil.close();
line.close();
}
}

Input:

This is file as input:
Demo.java
class Demo
 {
public static void main(java Demo beta gamma delta)
 {
 int n = 1 ;
 System.out.println(“The word is ” + args[ n ] );
 }
 }

Output:

Recommended Post:

Get Salesforce Answers

Pramod Kumar Yadav is from Janakpurdham, Nepal. He was born on December 23, 1996, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India.He is director of Appan Bazaar Pvt.Ltd., as teacher in Tridev Eng. School , and an Educational Consultant, and he is currently working as a developer and Digital Marketer.



5 thoughts on “Write a Java program that reads a file and displays the file on the screen with a line number before each line”

Leave a Comment