0

So I want to accept a file name from the user. I then want to check if the last four characters of the string are ".txt". If they aren't, append ".txt" to the end of the user inputted string. If they are, skip. Simple.

But it's not working - when I enter "exampledata.txt" it still adds ".txt" and throws a FileNotFoundException - and I can't figure out why. I've taken the same calculation and printed it out/verified in debugger; my method call to substring is correct.

Relevant code:

import java.util.*; 
import java.io.*;

public class MappingApp {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 
        String userInput;
        System.out.print("Enter file to read from: ");
        userInput = sc.nextLine();

        if ( (userInput.substring(userInput.length()-4, userInput.length())) != ".txt" ) {
            userInput += ".txt";
        }

        try {
            File f = new File(userInput);
            BufferedReader br = new BufferedReader(new FileReader(f));
        }
        catch (FileNotFoundException e) {
            System.err.println(e);
        }
    } 
}

1 Answers1

0

Usually you don't compare strings as != or == Try changing

if ( (userInput.substring(userInput.length()-4, userInput.length())) != ".txt" )

to

if ( !(userInput.substring(userInput.length()-4, userInput.length()).equals (".txt") )

Hope this will help.

Mithun Adhikari
  • 521
  • 6
  • 13