簡體   English   中英

java中如何定義相對路徑

[英]How to define a relative path in java

這是我的項目的結構:

這是我項目的結構

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

嘗試這樣的事情

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(String pathname) 中,Javadoc 的 File 類說

路徑名,無論是抽象的還是字符串形式的,都可以是絕對的或相對的。

如果要獲取相對路徑,必須定義從當前工作目錄到文件或目錄的路徑。嘗試使用系統屬性來獲取。如你繪制的圖片:

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

而且,你應該盡量避免使用類似的“.”、“../”、“/”等類似的相對於文件位置的相對路徑,因為當文件被移動時,更難處理。

 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

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

File myFolder = new File("directory"); 

不指向根元素。 例如,當您將應用程序放在C:驅動器 ( C:\\myApp.jar ) 上時, myFolder指向 (windows)

C:\Users\USERNAME\directory

代替

C:\Directory
 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();
                }
            }
        }

    }

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

我在使用我的圖像文件的相對路徑將屏幕截圖附加到 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);

Spring Boot 的示例。 我的 WSDL 文件位於“wsdl”文件夾中的資源中。 WSDL 文件的路徑是:

資源/wsdl/WebServiceFile.wsdl

要從某個方法獲取此文件的路徑,您可以執行以下操作:

String pathToWsdl = this.getClass().getClassLoader().
                    getResource("wsdl\\WebServiceFile.wsdl").toString();

由於 Java 7 你有Path.relativize()

“...一個 Path 還定義了 resolve 和 resolveSibling 方法來組合路徑。可用於在兩個路徑之間構造相對路徑的 relativize 方法。”

如果根據您的圖表,該文件位於您的src文件夾上方 2 級,則您應該使用以下相對路徑:

../../config.properties

請注意,在相對路徑中我們使用正斜杠/而不是反斜杠\

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM