gpt4 book ai didi

java - 如何在java中定义相对路径

转载 作者:IT老高 更新时间:2023-10-28 20:52:55 25 4
gpt4 key购买 nike

这是我的项目的结构:

here is the structure of my project

我需要阅读 MyClass.java 中的 config.properties。我尝试使用如下相对路径:

// Code called from MyClass.java
File f1 = new File("..\\..\\..\\config.properties");
String path = f1.getPath();
prop.load(new FileInputStream(path));

这给了我以下错误:

..\..\..\config.properties (The system cannot find the file specified)

如何在 Java 中定义相对路径?我正在使用 jdk 1.6 并在 windows 上工作。

最佳答案

试试这样的

String filePath = new File("").getAbsolutePath();
filePath.concat("path to the property file");

因此您的新文件指向创建它的路径,通常是您的项目主文件夹。

[编辑]

正如@cmc 所说,

    String basePath = new File("").getAbsolutePath();
System.out.println(basePath);

String path = new File("src/main/resources/conf.properties")
.getAbsolutePath();
System.out.println(path);

两者都给出相同的值。

关于java - 如何在java中定义相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14209085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com