如何在Java中定义相对路径

60

这是我的项目结构:

这是我的项目结构

我需要在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上工作。


3
那在Windows中是一个有效的相对路径..但是你所链接的位置不正确。(提示,它是相对于当前工作目录而不是源文件。) - user166390
你应该将你的 config.properties 文件放在 src 目录下。在 src 目录下创建一个名为 config 的包,并将 config.properties 文件放在 config 包中。然后可以通过访问 config/config.properties 来简单地获取它。 - Nandkumar Tekale
1
config.properties 会随着 Jar 文件一起分发吗?如果是这样的话,它将成为一个 [tag:embedded-resource],无法通过 File 访问,而必须通过 URL 访问。 - Andrew Thompson
是的,它与jar文件一起分发。 - ishk
9个回答

95

试试这样做

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

两者给出相同的值。


在创建 File("") 时,参数应该是你项目中文件的路径,而不是 "" - IgorGanapolsky

7
首先,了解绝对路径和相对路径的区别(点击此处)

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

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

在构造函数File(String pathname)中,Javadoc的File类指出:

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

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

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

此外,您应该尽量避免使用类似的“.”,“../”,“/”和其他类似相对于文件位置的路径,因为当文件被移动时,处理起来更加困难。

4
 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

我该如何在这里编写相对路径? - ishk
@ishk 我不知道Java是否支持通过包进行相对访问,我们可以像上面所说的那样从项目目录访问文件,并访问子文件夹。例如:File f = new File("folder/filename.txt"); - Abin Manathoor Devasia

2
值得一提的是,在某些情况下。
File myFolder = new File("directory"); 

如果您将应用程序放在C:驱动器(C:\myApp.jar)上时,myFolder指向的不是根元素。例如,对于Windows系统来说。

C:\Users\USERNAME\directory

替代

C:\Directory

1

这是一个Spring Boot的例子。我的WSDL文件在"wsdl"文件夹的资源中。WSDL文件的路径是:

resources/wsdl/WebServiceFile.wsdl

要从某个方法获取到该文件的路径,您可以按照以下步骤操作:
String pathToWsdl = this.getClass().getClassLoader().
                    getResource("wsdl\\WebServiceFile.wsdl").toString();

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");
来处理文件路径。

1
我在使用相对路径将截图附加到ExtentReports时遇到了问题,我的图片文件位于当前执行目录"C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic"下。在此目录下,我创建了一个名为ExtentReports的文件夹,其中包含report.html和image.png截图。请注意保留HTML标签。
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);

0

如果根据您的图表,文件位于src文件夹的上面2个级别,则应使用以下相对路径:

../../config.properties

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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接