如何从 Java 项目中的相对路径读取文件? Java.io.File 无法找到指定的路径

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

  1. tkorg.idrs.core.searchengines
  2. tkorg.idrs.core.searchengines

在包(2)中我有一个文本文件 ListStopWords.txt,在包(1)中我有一个类 FileLoadder。以下是 FileLoader中的代码:

File file = new File("properties\\files\\ListStopWords.txt");

但我有一个错误:

系统找不到指定的路径

你能解决这个问题吗?

679012 次浏览

试试 .\properties\files\ListStopWords.txt

如果它已经在类路径中,那么只需从类路径获取它,而不是从磁盘文件系统获取它。不要在 java.io.File中修改相对路径。它们取决于当前的工作目录,而你完全无法从 Java 代码内部控制它们。

假设 ListStopWords.txtFileLoader类在同一个包中,那么执行以下操作:

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

或者,如果你最终追求的只是它的一个 InputStream:

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

这当然优于创建 new File(),因为 url可能不一定代表磁盘文件系统路径,但是它也可以代表虚拟文件系统路径(当 JAR 扩展到内存而不是磁盘文件系统上的临时文件夹时可能会发生这种情况)或者甚至是一个网络路径,这两者都不符合 File构造函数的定义。

如果这个文件——如包名所示——是 事实上一个完整的 属性档案(包含 key=value行) ,只有“错误的”扩展名,那么您可以立即将 InputStream提供给 load()方法。

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

注意: 当您试图从 static上下文中访问它时,在上面的示例中使用 FileLoader.class(或任何 YourClass.class)而不是 getClass()

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();
}

如果要指定文件的相对路径,可以使用以下行。

File file = new File("./properties/files/ListStopWords.txt");

如果您试图从静态方法或静态块调用 getClass(),您可以采用以下方法。

可以对要加载到的 Properties对象调用 getClass()

    public static Properties pathProperties = null;
    

static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml";
//      Now go for getClass() method
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}

尽管 BalusC 提供的答案适用于这种情况,但是当文件路径包含空格时,它会中断,因为在 URL 中,这些空格被转换为% 20,而这不是一个有效的文件名。如果使用 URI 而不是 String 构造 File 对象,则可以正确处理空白:

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

相对路径在 Java 中使用 .说明符工作。

  • .表示与当前运行的上下文相同的文件夹。
  • ..表示当前运行上下文的父文件夹。

所以问题是你怎么知道 Java 当前的路径?

做个小实验

   File directory = new File("./");
System.out.println(directory.getAbsolutePath());

观察输出,你就会知道 Java 的工作目录。从那里,只需使用 ./说明符来定位您的文件。

例如,如果输出为

G: JAVA8Ws MyProject 内容。

你的文件在“我的项目”文件夹中,只需使用

File resourceFile = new File("../myFile.txt");

希望这个能帮上忙。

如果未读取文本文件,请尝试使用更接近的绝对路径(如果愿意) 你可以使用完全绝对路径,)像这样:

FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");

假设绝对路径是:

C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt

我想在 src/main//js/Simulator.java 中解析‘ command.json’。为此,我复制了 src 文件夹中的 json 文件,并给出了如下绝对路径:

Object obj  = parser.parse(new FileReader("./src/command.json"));

我本可以发表评论的,但是我的名声比较小。 萨姆拉特的回答帮了我的忙,最好通过下面的代码看到工作目录的路径。

    File directory = new File("./");
System.out.println(directory.getAbsolutePath());

我只是用它来纠正我在项目中遇到的一个问题。一定要用。/返回到工作目录的父目录。

    ./test/conf/appProperties/keystore

enter image description here

假设要从 FileSystem类中的 resources目录读取。

String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);


System.out.println(Files.readString(path));

注: 前导 .不需要。

对我来说,实际上问题是 File 对象的类路径来自 <project folder path> or ./src,所以使用 File file = new File("./src/xxx.txt");解决了我的问题

String basePath = new File (“ myFile.txt”) . getAbsolutePath () ; 这个基路径可以用作文件的正确路径

对我来说,它工作与-

    String token = "";
File fileName = new File("filename.txt").getAbsoluteFile();
Scanner inFile = null;
try {
inFile = new Scanner(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( inFile.hasNext() )
{
String temp = inFile.next( );
token = token + temp;
}
inFile.close();
    

System.out.println("file contents" +token);

如果要从 src 文件夹中的资源文件夹加载属性文件,请使用

String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();
p.load(resourceStream);
      

System.out.println(p.getProperty("db"));

Properties 文件包含键和值 db=sybase