如何获取项目中文件的路径以使用 OpenCSV 读取它

How to get the path of a file inside a project to read it with OpenCSV

我在源文件夹内的文件夹中有一个 CSV 文件,但我无法访问它。

我将它与我在互联网上找到的内容一起使用:

URL url = getClass().getResource("/csv/recetas.csv");
File file = new File(url.getPath());
FileReader fileReader = new FileReader(file);
CSVReader csvReader = new CSVReader(fileReader, ',', '"', 1);

但它只在我 运行 它在 IDE 时有效。当我构建 jar 并尝试 运行 它时,FileReader 找不到该文件,它不会为 URL 或 File 抛出错误。

这是我的project folder所以你可以理解我。谢谢

InputStream in = getClass().getResourceAsStream("/csv/recetas.csv");
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
CSVReader(reader, ',', '"', 1);

资源 是 class 路径 "files" 可能打包在一个罐子里。它们 不是 File,并且是只读的。

同样为了兼容性,明确给出字符集。

getClass().getResource()使用class加载器加载资源。这意味着您的 csv 文件将不可见,除非它位于 classpath.

再次查看您的代码和问题,getClass().getResource() 对我来说似乎是多余的,因为 File(...) 的构造函数接受描述为字符串的文件路径。

见: https://docs.oracle.com/javase/7/docs/api/java/io/File.html

引用:

File(String pathname) Creates a new File instance by converting the given pathname string into an abstract pathname.

为了使您的程序更加通用,我建议您避免对文件路径进行硬编码,因为 csv 文件可以位于文件系统中的任何位置,并且它可能并不总是被调用 recetas.csv

人们通常会做的是让 java 程序接受像 --csv 这样的选项。然后让用户指定文件路径,您的代码将只是 new File(theSpecifiedPath).