如何从Java项目中的相对路径读取文件? java.io.File找不到指定的路径 [英] How to read file from relative path in Java project? java.io.File cannot find the path specified

查看:979
本文介绍了如何从Java项目中的相对路径读取文件? java.io.File找不到指定的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个包的项目:

I have a project with 2 packages:


  1. tkorg.idrs.core.searchengines

  2. tkorg.idrs.core.searchengines

  1. tkorg.idrs.core.searchengines
  2. 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. 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 FileLoader class:

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());

或者如果你所有的都是一个 InputStream 它:

Or if all you're after is an InputStream of it:

InputStream input = getClass().getResourceAsStream("ListStopWords.txt");

如果文件是 - 包名称hints-是实际全面的属性文件(包含 key =值行),只需错误的扩展名,那么您可以立即将其提供给 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 it immediately to the load() method.

Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));

注意:当您尝试从 static 上下文,然后在上面的例子中使用 FileLoader.class 而不是 getClass()

Note: when you're trying to access it from inside static context, then use FileLoader.class instead of getClass() in above examples.

这篇关于如何从Java项目中的相对路径读取文件? java.io.File找不到指定的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆