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.text.*;

public class countCharacters {  
	public void Charact() throws IOException {  
		Scanner sc = new Scanner(;//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 =;//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
        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

Recommended Answers

All 3 Replies

and how would that ever work?
I can name anything at all ".txt" even if it's not a ".txt" file (whatever that means), or I could have a ".txt" file that has a completely different name.
You'll have to find some way to determine whether a file is a ".txt" file based on the file content, not name.

I think if file contains .txt at the last then it will be text file only, otherwise after reading u cant decide if it is .txt file or .csv file.
chk for the last string if last string is .txt it will be txt file only.
you can check for str.substring(str.lastIndexOf("."), str.length())

You should consider jwenting's reply, but if you only care about the extension for some reason, and don't care about the contents, you can use a Regular Expression to check.

Something like

(.*)(\.txt)$ might work. I haven't tried it but you can check out Regular Expressions tutorial here. The idea of '$' is to force it to be at the end of the line. The '\' before the '.' is because '.' is usually interpreted as "anything" but we want to interpret it as a literal '.' character. The ".*" means find any characters, 0 or more times, and also take a greedy approach.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.