gpt4 book ai didi

java - 在 Eclipse 中读取项目中的 .txt 文件

转载 作者:行者123 更新时间:2023-12-02 03:45:13 26 4
gpt4 key购买 nike

嗯,我知道这个问题已被问过多次,但尽管遵循这些链接中的所有建议,我仍然最终收到文件未找到错误。

这些是我已经检查过的链接。

Where do I put the txt file that I want to read in Java?

How to really read text file from classpath in Java

所以请不要让触发器高兴地将其标记为重复。

大多数链接似乎可以互换使用 ClassPath 和 BuildPath 这个词,它们是同一个东西吗?因为在我的 IDE 中我似乎找不到与 ClassPath 相关的任何内容,它只是 BuildPath。

这是我的目录结构。

enter image description here

调用者类需要该文件

enter image description here

我已经尝试了链接中的几乎所有内容,但仍然无法读取该文件。

读取文件的代码在这里

String path = "DataSource/data1.txt";
String jsonData = null;

try {

jsonData = Reader.readFile(path);
} catch (Exception e) {
e.printStackTrace();
}

感谢任何帮助。

最佳答案

尝试

String path = "src/main/java/DataSource/data1.txt";

了解 eclipe 中的执行点位于项目根目录。

但是您可能想将此类资源打包到您的 jar 上。如果是这样,您需要使用类似以下内容:

jsonData = Reader.readFile(Caller.class.getResourceAsStream("DataSource/data1.txt""));

最后,将 .txt 文件移动到“src/main/resources”,因为这是一个很好的做法。

关于java - 在 Eclipse 中读取项目中的 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36358439/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com