Java Program to read a file

// read a file and display the number of lines and characters.

import java.io.*;
import java.util.*;
class FileRead
{
public static void main(String s[]) throws Exception
{
int nl=0,nc=0;
String str,line;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the file name");
str=br.readLine();
File f=new File(str);
if(f.exists())
{
BufferedReader b=new BufferedReader(new FileReader(str));
while((line=b.readLine())!=null)
{
nl++;
nc+=line.length();
System.out.println(line);
}
System.out.println("Number of Lines: "+nl);
System.out.println("NUmber of characters: "+nc);
}
else
{
System.out.println("File does not exist!");
}
}
}

Output


java program to read file

No comments: