In the code below I am opening a .txt file to count the characters in it. I am assuming that the user does enter a .txt file, but how can I go in checking that the file is truly a .txt. I was thinking of using a java function to check for an occurrence of a string in the file name that contains the extension .txt but that would not work if for some reason the user enters .txt.txt (even though this input would be incorrect)
import java.util.*;
import java.io.*;
import java.text.*;
public class countCharacters {
public void Charact() throws IOException {
Scanner sc = new Scanner(System.in);//declare scanner
String fName;//creates string variable used to store the name of the file
System.out.println("Please Enter The Name Of A .txt File: ");//prompt user to enter file name
fName = sc.next();//takes in file name
File f = new File(fName);
FileReader fr = new FileReader(f);//creates
BufferedReader br = new BufferedReader(fr);
long numChar = f.length();//stores the total number of characters
int countChar =0 ;//initializes variable
while(countChar<numChar)//loop counts characters until all have been counted
{
countChar++;
}
System.out.println("Filename: " + fName);//prints name of the file
System.out.println("Number of Characters In The File: " + countChar);//prints number of characters in the file
}
public static void main(String args[]) throws IOException {
countCharacters ob1 = new countCharacters();//creates an instance of the counCharacter class
ob1.Charact();//calls the charact function
}
}