在intelliJ中从Java中的文件读取
我正在从Eclipse切换到IntelliJ。我已经在我的项目中包含了一个文件input.txt,但是当我编写Java代码来访问它时,我得到了一个FileNotFoundException。我做错了什么在intelliJ中从Java中的文件读取,java,io,intellij-idea,Java,Io,Intellij Idea,我正在从Eclipse切换到IntelliJ。我已经在我的项目中包含了一个文件input.txt,但是当我编写Java代码来访问它时,我得到了一个FileNotFoundException。我做错了什么 这不是问题所在,在IntelliJ中找不到该文件。事实上,您的编译器说,在运行时可能找不到该文件。 因此,您必须使用try-catch块处理FileNotFoundException,如下所示: try { BufferedReader reader = new BufferedRead
这不是问题所在,在IntelliJ中找不到该文件。事实上,您的编译器说,在运行时可能找不到该文件。 因此,您必须使用try-catch块处理FileNotFoundException,如下所示:
try {
BufferedReader reader = new BufferedReader(new FileReader("./input.txt"));
// read the file
// ...
} catch (FileNotFoundException e) {
// do something, when the file could not be found on the system
System.out.println("The file doesn't exist.");
} catch (IOException e) {
// do something, when the file is not readable
System.out.println("The file could not be read.");
} catch (/* other exceptions... */) {
// do something else on some other exception
// ...
}
当然,您已经知道,将找到文件,但不会找到编译器
基本上阅读有关异常的内容:这不是问题所在,在IntelliJ中找不到该文件。事实上,您的编译器说,在运行时可能找不到该文件。 因此,您必须使用try-catch块处理FileNotFoundException,如下所示:
try {
BufferedReader reader = new BufferedReader(new FileReader("./input.txt"));
// read the file
// ...
} catch (FileNotFoundException e) {
// do something, when the file could not be found on the system
System.out.println("The file doesn't exist.");
} catch (IOException e) {
// do something, when the file is not readable
System.out.println("The file could not be read.");
} catch (/* other exceptions... */) {
// do something else on some other exception
// ...
}
当然,您已经知道,将找到文件,但不会找到编译器
基本上阅读有关异常的内容:您也可以将FileNotFoundException抛出到主方法中,您的输出将不会那么漂亮
public static void main(String[] args) throws FileNotFoundException {
您还可以将FileNotFoundException抛出到主方法中,这样您的输出就不会那么漂亮了
public static void main(String[] args) throws FileNotFoundException {
您应该指定文件的完整路径,或者运行程序,使其工作目录包含此文件。如果转到运行配置设置并确保“工作目录”字段指向Hexagram目录,则可以实现第二个目标。您应该指定文件的完整路径或运行程序,使其工作目录包含此文件。如果转到运行配置设置并确保Working DIrectory字段指向Hexagram目录,则可以实现第二个错误。这并不能真正解决引发错误的原因。考虑将其作为对问题的评论,而这并不能真正解释为什么错误被抛出。考虑把它作为对这个问题的评论,是的,我没有处理这个例外。但是现在当我运行程序时,我看到错误消息:文件不存在。是的,我确实没有处理异常。。但是现在当我运行程序时,我看到错误消息:文件不存在。