Samolivercz
Samolivercz

Reputation: 220

Trying to allow a user to select a text file using a Scanner

As the title says I'm trying to allow a user enter the name of the file they want to select, in order for my program to analyse that text file. However when I enter the name of the text file, which is "test.txt" I receive a file not found error, the file is in the same directory as the class which is why I am so confused as to why it doesn't work, could someone help explain what I'm doing wrong here?

This is the code I have:

   Scanner in = new Scanner(System.in);
   System.out.print("Enter filename: ");
   String filename = in.nextLine();
   File InputFile = new File(filename);

   Scanner reader = new Scanner(InputFile);

The Error:

Enter filename: test.txt //Here is what I have entered after being prompted.
Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)

Thanks!

Upvotes: 0

Views: 262

Answers (2)

Kick Buttowski
Kick Buttowski

Reputation: 6739

How to deal with the FileNotFoundException

  1. If the message of the exception claims that there is no such file or directory, then you must verify that the specified is correct and actually points to a file or directory that exists in your system.

  2. If the message of the exception claims that permission is denied then, you must first check if the permissions of the file are correct and second, if the file is currently being used by another application.

  3. If the message of the exception claims that the specified file is a directory, then you must either alter the name of the file or delete the existing directory (if the directory is not being used by an application).

Important:

For those developers that use an IDE to implement their Java applications, the relative path for every file must be specified starting from the level where the src directory of the project resides.

Note: Your issue is number option one.

What I do to resolve this issue?

  1. I usually use absolute path which I do not recommend because it is just Micky Mouse job.

  2. Use relative path because your program will be path independent.

Upvotes: 1

clsbartek
clsbartek

Reputation: 206

From java docs:

public Scanner(File source) throws FileNotFoundException

Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.

Parameters: source - A file to be scanned Throws: FileNotFoundException - if source is not found

You should just call

InputFile.createNewFile();

before

 Scanner reader = new Scanner(InputFile);

Upvotes: 0

Related Questions