简体   繁体   中英

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;

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

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 '/'.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM