简体   繁体   English

FileNotFoundException。 如何构造文件路径?

[英]FileNotFoundException. How to construct a file path?

I am trying create Scanner object, but I can't because FileNotFoundException: image link 我正在尝试创建Scanner对象,但不能这样做,因为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. Windows以'\\'反斜杠作为文件分隔符。 Also this will require '\\\\' as backslash is an escape character in Java. 此外,这将需要'\\\\',因为反斜杠是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. 如果File.Separator旨在不用于您的系统,则可以使用File.Separator,因为它会根据Mac或Windows的不同而有所不同。

https://docs.oracle.com/javase/7/docs/api/java/io/File.html#separator 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. 这里发生的是您的IDE(从外观上看是IntelliJ)警告您该代码引发了FileNotFoundException。 You should try wrapping the code in a try/catch block like so: 您应该尝试将代码包装在try/catch块中,如下所示:

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. 另外,正如其他人所述,Windows使用反斜杠('\\')作为文件分隔符。 Whereas UNIX systems use '/'. UNIX系统使用'/'。

You should always surround this kind of error prone code in a try/catch block 您应该始终在try / catch块中包含这种容易出错的代码

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. 您指定的文件必须在项目的根目录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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