Adrian
Adrian

Reputation: 43

FileNotFoundException. How to construct a file path?

I am trying create Scanner object, but I can't because FileNotFoundException: image link

Scanner regionData = new Scanner(new File("RU.txt"));

Libraries

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

Upvotes: 0

Views: 59

Answers (3)

ClarksonDev
ClarksonDev

Reputation: 75

You should always surround this kind of error prone code in a try/catch block

Scanner regionData = null;

try {
   regionData = newScanner(new File("RU.txt"));
} catch (FileNotFoundException e) {
   // handle what happens if exception is thrown
}

The file you specified needs to be in your root directory for the project.

Upvotes: 0

user4205830
user4205830

Reputation:

What's happening here is that your IDE (IntelliJ by the looks of it) is warning you that the code threw a FileNotFoundException. You should try wrapping the code in a try/catch block like so:

try {
    Scanner regionData = new Scanner(new File("RU.txt"));
} catch (FileNotFoundException e) {
    // Handle the error here. e.g.,
    e.printStackTrace();
}

Also, as mentioned by others, Windows uses the backslash ('\') as the file separator. Whereas UNIX systems use '/'.

Upvotes: 1

Airo
Airo

Reputation: 68

Windows is '\' backslash as the file separator. Also this will require '\\' as backslash is an escape character in Java. It is smart to use File.Separator if this is meant for use not on your system as it will change depending on say Mac or Windows.

https://docs.oracle.com/javase/7/docs/api/java/io/File.html#separator

Upvotes: 1

Related Questions