簡體   English   中英

Java中的相對文件路徑

[英]Relative file path in java

我有以下代碼:

 Process p = Runtime.getRuntime().exec(command.toString(), null, 
                                          new File("D:\\Cognity"));

但是問題是Cognity目錄並不總是在D:\\中,它可能在C:\\等中。所以我的問題是是否有辦法給它一個相對路徑,所以我不必更改此代碼,具體取決於在使用該程序的PC上?

作為System.getProperty("user.dir")); 返回啟動JVM的目錄,您仍然不能保證您是在C:\\還是D:\\中。我的建議是將Cognity位置作為-D命令行參數傳遞並按如下方式使用:

Process p = Runtime.getRuntime().exec(command.toString(), null, new File(System.getProperty("cognity.dir")));

當然可以。

調用System.getProperty("user.dir")); 獲取當前目錄,並連接到結果的相對路徑。

例如

String path=System.getProperty("user.dir"));
path+=realtivePath;

編輯:

Calrification:

例如:您要運行的程序始終位於向后兩個文件夾,然后位於Temp dir。

因此,相對路徑為..\\\\..\\Temp\\prog.exe.

假設在一台計算機上,您的程序位於C:\\ Users \\ user \\ Documents \\ Program,因此這是工作目錄。

所以:

String path=System.getProperty("user.dir")); //returns the working directory
String realtivePath="\\ ..\\..\\Temp"; //no matter what is the first path, this is the relatuve location to the current dir
path+=realtivePath;
//in this example, path now equals C:\Users\user\Documents\Program\..\..\Temp\prog.exe = C:\Users\user\Temp\prog.exe
Process p = Runtime.getRuntime().exec(command.toString(), null, new File(path));

您可以使用config-File來設置絕對路徑,也可以在jar文件的相對路徑中創建該目錄。

暫無
暫無

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

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