如何从Java项目中的相对路径读取文件?java.io.File 找不到指定的路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3844307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read file from relative path in Java project? java.io.File cannot find the path specified
提问by tiendv
I have a project with 2 packages:
我有一个包含 2 个包的项目:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt
, in package (1) I have a class FileLoadder
. Here is code in FileLoader
:
在包 (2) 中,我有一个文本文件ListStopWords.txt
,在包 (1) 中,我有一个类FileLoadder
。这是代码FileLoader
:
File file = new File("properties\files\ListStopWords.txt");
But have this error:
但是有这个错误:
The system cannot find the path specified
Can you give a solution to fix it? Thanks.
你能给出解决方法吗?谢谢。
采纳答案by BalusC
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.
如果它已经在类路径中,那么只需从类路径而不是从磁盘文件系统中获取它。不要摆弄java.io.File
. 它们依赖于您完全无法从 Java 代码内部控制的当前工作目录。
Assuming that ListStopWords.txt
is in the same package as your FileLoader
class, then do:
假设它ListStopWords.txt
与您的FileLoader
课程在同一个包中,然后执行以下操作:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream
of it:
或者,如果您最终所追求的只是其中InputStream
之一:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
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.
这当然比创建 a 更受欢迎,new File()
因为它url
可能不一定代表磁盘文件系统路径,但它也可以代表虚拟文件系统路径(当 JAR 扩展到内存中而不是磁盘文件系统上的临时文件夹时,可能会发生这种情况)甚至是File
构造函数都不能根据定义消化的网络路径。
If the file is -as the package name hints- is actuallya fullworthy properties file(containing key=value
lines) with just the "wrong" extension, then you could feed the InputStream
immediately to the load()
method.
如果该文件 - 作为包名称提示 -实际上是一个完整的属性文件(包含key=value
行),只有“错误”的扩展名,那么您可以InputStream
立即将 提供给该load()
方法。
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
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.
注意:当您尝试从内部static
上下文访问它时,请使用FileLoader.class
(或其他YourClass.class
)而不是getClass()
上面的示例。
回答by bUg.
try .\properties\files\ListStopWords.txt
尝试 .\properties\files\ListStopWords.txt
回答by frictionlesspulley
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
回答by santhosh
The following line can be used if we want to specify the relative path of the file.
如果我们要指定文件的相对路径,可以使用以下行。
File file = new File("./properties/files/ListStopWords.txt");
回答by arun_kk
If you are trying to call getClass()
from Static method or static block the you can do the following way.
如果您尝试getClass()
从静态方法或静态块调用,您可以按以下方式进行。
You can call getClass()
on the Properties
object you are loading into.
您可以调用要加载到getClass()
的Properties
对象。
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml;
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}
回答by Mark Krijgsman
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
虽然 BalusC 提供的答案适用于这种情况,但当文件路径包含空格时它会中断,因为在 URL 中,这些将被转换为 %20,这不是有效的文件名。如果您使用 URI 而不是 String 构造 File 对象,空格将被正确处理:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
回答by Samrat
The relative path works in in java using the . operator.
相对路径在 java 中使用 . 操作员。
- . means same folder as the currently running context.
- .. means the parent folder of the currently running context.
- . 表示与当前运行的上下文相同的文件夹。
- .. 表示当前运行上下文的父文件夹。
So the question is how do you know the path where the java is currently looking?
所以问题是你如何知道java当前正在寻找的路径?
do a small experiment
做一个小实验
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output , you will come to know the current directory where java is looking . From there , simply use the ./ operator to locate your file.
观察输出,你会知道java正在查找的当前目录。从那里,只需使用 ./ 运算符来定位您的文件。
for example if the output is
例如,如果输出是
G:\JAVA8Ws\MyProject\content.
G:\JAVA8Ws\MyProject\内容。
and your file is present in the folder MyProject simply use
并且您的文件存在于文件夹 MyProject 中,只需使用
File resourceFile = new File("../myFile.txt");
Hope this helps
希望这可以帮助
回答by KR N
If text file is not being read, try using a more closer absolute path (if you wish you could use complete absolute path,) like this:
如果没有读取文本文件,请尝试使用更接近的绝对路径(如果您希望可以使用完整的绝对路径),如下所示:
FileInputStream fin=new FileInputStream("\Dash\src\RS\Test.txt");
assume that the absolute path is:
假设绝对路径是:
C:\Folder1\Folder2\Dash\src\RS\Test.txt
回答by sver
I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :
我想解析 src/main//js/Simulator.java 中的“command.json”。为此,我在 src 文件夹中复制了 json 文件,并给出了这样的绝对路径:
Object obj = parser.parse(new FileReader("./src/command.json"));
回答by backbenchor
I could have commented but I have less rep for that. Samrat's answer did the job for me. It's better to see the current directory path through the following code.
我可以发表评论,但我的代表较少。Samrat 的回答为我完成了这项工作。最好通过以下代码查看当前目录路径。
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.
我只是用它来纠正我在项目中遇到的问题。一定要使用 ./ 回到当前目录的父目录。
./test/conf/appProperties/keystore