我有一个包含2个包的项目:
tkorg.idrs.core.searchenginestkorg.idrs.core.searchengines在包(2)中我有一个文本文件ListStopWords.txt,在包(1)中我有一个类FileLoadder.这是代码FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
Run Code Online (Sandbox Code Playgroud)
但有这个错误:
The system cannot find the path specified
Run Code Online (Sandbox Code Playgroud)
你能解决一下吗?谢谢.
Bal*_*usC 155
如果它已经在类路径中,那么只需从类路径中获取它.不要乱用相对路径java.io.File.它们依赖于当前工作目录,您无法完全控制Java代码.
假设它ListStopWords.txt与FileLoader类在同一个包中:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Run Code Online (Sandbox Code Playgroud)
或者,如果你所追求的只是一个InputStream:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
Run Code Online (Sandbox Code Playgroud)
如果该文件是-as包名hints-是其实一个fullworthy 属性文件(含new File()线),只是"错误"的延伸,那么你可以立刻给它的url方法.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Run Code Online (Sandbox Code Playgroud)
注意:当您尝试从内部File上下文中访问它时,请使用key=value而不是InputStream上面的示例.
小智 42
如果我们要指定文件的相对路径,可以使用以下行.
File file = new File("./properties/files/ListStopWords.txt");
Run Code Online (Sandbox Code Playgroud)
Sam*_*rat 35
相对路径在java中使用.运营商.
所以问题是你如何知道java目前正在寻找的路径?
做一个小实验
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)
观察输出,您将了解java正在查找的当前目录.从那里,只需使用./运算符来定位您的文件.
例如,如果输出是
G:\ JAVA8Ws\MyProject的\内容.
并且您的文件存在于MyProject简单使用的文件夹中
File resourceFile = new File("../myFile.txt");
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
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();
}
Run Code Online (Sandbox Code Playgroud)
resources假设您想从课堂上的目录中读取内容FileSystem。
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Run Code Online (Sandbox Code Playgroud)
注意:.不需要领先。
我可以发表评论,但我的代表较少。Samrat 的回答为我完成了这项工作。最好通过以下代码查看当前目录路径。
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)
我只是用它来纠正我在项目中遇到的问题。一定要使用 ./ 回到当前目录的父目录。
./test/conf/appProperties/keystore
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
484766 次 |
| 最近记录: |