使用 Intellij IDEA IDE 读取文件

2022-01-20 00:00:00 file ide intellij-idea java

我是一个长期的 eclipse 用户,我已经开始使用 IntelliJ IDEA.

I am a long time eclipse user and I have started to play around with IntelliJ IDEA.

所以据我了解,IntelliJ 中的项目与 Eclipse 工作区相同.此外,IntelliJ 中的模块相当于 Eclipse 中的项目.

So from my understanding, a project in IntelliJ is the same as the Eclipse workspace. Additionally, a module in IntelliJ is the equivalent of a project in Eclipse.

我在 IntelliJ 中创建了一个项目,但我仍然不确定如果它应该是一个工作区,为什么会有一个 src 文件夹.

I created a project in IntelliJ, but I’m still not sure why there is a src folder in it if it is supposed to be a workspace.

之后,我在项目中创建了一个模块,并在新模块的 src 目录中创建了一个类,代码如下:

Afterwards, I created a module in the project and a class inside the src directory of the new module with this code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MainClass {
    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("Hello World!");
        Scanner input = new Scanner(new File ("test123.txt"));
        String answer = input.nextLine();
        System.out.println(answer);
    }
}

问题是我尝试读取文件时出错.我尝试将 .txt 文件放在我的 src 文件中,该文件位于模块内部和 src 目录之外但在模块内部.但在这两种情况下都找不到文件.是的,代码有效,我在 Eclipse 上尝试过,它工作正常.文件名也拼写正确.

The problem is that I get an error trying to read the file. I tried putting the .txt file inside my src file which is located inside the module and outside the src directory but inside the module. But in both cases the file is not found. Yes the code works, I tried it on Eclipse and it works fine. The file name is spelled correctly as well.

如果有帮助,这是我的项目/工作区的图片:

Here is a picture of my project/workspace if it is helpful:

推荐答案

只需将文件直接移动到调用 Java 的项目文件夹(以及您制作的蓝色模糊条纹下的东西:P).

Just move the file directly to the project folder which calls Java (and something under the blue-blurred stripe you made :P).

如果这没有帮助,则将 test123.txt 文件移动到 FirstJavaProgram 目录.

If that doesn't help, then move the test123.txt file to FirstJavaProgram directory.

您还可以将文件名更改为以下之一:

You can also change filename to one of these:

  1. src/test123.txt

FirstJavaProgram/src/test123.txt

我不确定哪一个适合你的情况.

I am not sure which one will be fine in your case.

相关文章