如何从Java项目中的相对路径读取文件?java.io.File 找不到指定的路径 [英] How to read file from relative path in Java project? java.io.File cannot find the path specified
问题描述
我有一个包含 2 个包的项目:
I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
在包 (2) 中,我有一个文本文件 ListStopWords.txt
,在包 (1) 中,我有一个类 FileLoadder
.这是FileLoader
中的代码:
In package (2) I have a text file ListStopWords.txt
, in package (1) I have a class FileLoadder
. Here is code in FileLoader
:
File file = new File("properties\files\ListStopWords.txt");
但是有这个错误:
The system cannot find the path specified
你能给出解决方法吗?谢谢.
Can you give a solution to fix it? Thanks.
推荐答案
如果它已经在类路径中,那么只需从类路径而不是从磁盘文件系统中获取它.不要在 java.io.File
中摆弄相对路径.它们依赖于您在 Java 代码内部完全无法控制的当前工作目录.
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File
. They are dependent on the current working directory over which you have totally no control from inside the Java code.
假设 ListStopWords.txt
与您的 FileLoader
类在同一个包中,然后执行:
Assuming that ListStopWords.txt
is in the same package as your FileLoader
class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
或者,如果你最终想要的实际上只是一个 InputStream
:
Or if all you're ultimately after is actually an InputStream
of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
这肯定比创建 new File()
更可取,因为 url
不一定代表磁盘文件系统路径,但它也可以代表虚拟文件系统路径(当 JAR 扩展到内存中而不是磁盘文件系统上的临时文件夹时,可能会发生这种情况)甚至网络路径都不是 File
构造函数可消化的每个定义.
This is certainly preferred over creating a new File()
because the url
may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File
constructor.
如果文件 - 如包名提示 - 实际上是一个完整的properties 文件(包含 key=value
行)只有错误"的扩展名,然后您可以立即提供 InputStream
到 load()
方法.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value
lines) with just the "wrong" extension, then you could feed the InputStream
immediately to the load()
method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
注意:当您尝试从 static
上下文中访问它时,请使用 FileLoader.class
(或任何 YourClass.class
) 而不是上面例子中的 getClass()
.
Note: when you're trying to access it from inside static
context, then use FileLoader.class
(or whatever YourClass.class
) instead of getClass()
in above examples.
这篇关于如何从Java项目中的相对路径读取文件?java.io.File 找不到指定的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!