52

这是我的项目的结构:

这是我的项目的结构

我需要在config.properties里面阅读MyClass.java。我尝试使用如下相对路径来执行此操作:

// 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 上工作。

4

9 回答 9

83

尝试这样的事情

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

两者都给出相同的值。

于 2013-01-08T06:08:16.997 回答
6

首先,在这里查看绝对路径和相对路径之间的区别:

绝对路径始终包含根元素和定位文件所需的完整目录列表。

或者,需要将相对路径与另一个路径组合才能访问文件。

在构造函数 File(String pathname) 中,Javadoc 的 File 类说

路径名,无论是抽象的还是字符串形式的,都可以是绝对的或相对的。

如果要获取相对路径,则必须定义从当前工作目录到文件或目录的路径。尝试使用系统属性来获取。如您绘制的图片:

String localDir = System.getProperty("user.dir");
File file = new File(localDir + "\\config.properties");

此外,应尽量避免使用类似“.”、“../”、“/”等类似相对文件位置的相对路径,因为文件移动时,比较难处理。

于 2018-01-28T04:27:12.790 回答
3
 File f1 = new File("..\\..\\..\\config.properties");  

试图访问文件的路径在项目目录中,然后像这样访问文件。

File f=new File("filename.txt");

如果您的文件在OtherSources/Resources

this.getClass().getClassLoader().getResource("relative path");//-> relative path from resources folder
于 2013-01-08T06:15:46.217 回答
2

值得一提的是,在某些情况下

File myFolder = new File("directory"); 

不指向根元素。例如,当您将应用程序放在C:驱动器 ( C:\myApp.jar) 上时,然后myFolder指向 (windows)

C:\Users\USERNAME\directory

代替

C:\Directory
于 2015-01-28T21:59:35.507 回答
1

我在使用图像文件的相对路径将屏幕截图附加到 ExtentReports 时遇到问题。执行时我的当前目录是“C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic”。在此之下,我为 report.html 和 image.png 截图创建了文件夹 ExtentReports,如下所示。

private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className  + ".html";
ExtentReports report;
ExtentTest test;

@BeforeMethod
    //  initialise report variables
    report = new ExtentReports(outputFolder + outputFile);
    test = report.startTest(className);
    // more setup code

@Test
    // test method code with log statements

@AfterMethod
    // takeScreenShot returns the relative path and filename for the image
    String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
    String imagePath = test.addScreenCapture(imgFilename);
    test.log(LogStatus.FAIL, "Added image to report", imagePath);

这会在 ExtentReports 文件夹中创建报告和图像,但是当打开报告并检查(空白)图像时,将鼠标悬停在图像 src 上会显示“无法加载图像”src=".\ExtentReports\QXKmoVZMW7.png"。

这可以通过使用系统属性“user.dir”为图像的相对路径和文件名添加前缀来解决。所以这完美地工作并且图像出现在html报告中。

克里斯

String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);
于 2017-03-10T16:40:38.420 回答
1
 public static void main(String[] args) {
        Properties prop = new Properties();
        InputStream input = null;
        try {
            File f=new File("config.properties");
            input = new FileInputStream(f.getPath());
            prop.load(input);
            System.out.println(prop.getProperty("name"));
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

您也可以使用
Path path1 =FileSystems.getDefault().getPath(System.getProperty("user.home"), "downloads", "somefile.txt");

于 2015-08-18T09:43:59.070 回答
1

Spring Boot 的示例。我的 WSDL 文件位于“wsdl”文件夹中的资源中。WSDL 文件的路径是:

资源/wsdl/WebServiceFile.wsdl

要从某个方法获取此文件的路径,您可以执行以下操作:

String pathToWsdl = this.getClass().getClassLoader().
                    getResource("wsdl\\WebServiceFile.wsdl").toString();
于 2018-02-14T15:24:52.550 回答
0

从 Java 7 开始,您拥有Path.relativize()

“... Path 还定义了 resolve 和 resolveSibling 方法来组合路径。relativize 方法可用于构造两条路径之间的相对路径。”

于 2021-09-27T07:34:09.460 回答
0

如果根据您的图表,该文件比您的src文件夹高 2 级,则应使用以下相对路径:

../../config.properties

请注意,在相对路径中,我们使用正斜杠/而不是反斜杠\

于 2021-10-03T07:11:29.967 回答