Java program to read and display files

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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();
	}
}

Output:

Demo.java

class Demo
1 {
2 public static void main(java Demo beta gamma delta)
3 {
4 int n = 1 ;
5 System.out.println(“The word is ” + args[ n ] );
6 }
7 }
8?

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in