![](/img/trans.png)
[英]$PATH is different when I run bash from java processbuilder
[英]Java ProcessBuilder Error When Space(s) In Path
因此,我花了半天的時間嘗試使此方法正常工作,但沒有取得積極的成果。 我正在使用Java ProcessBuilder執行帶有一些參數的某些.exe文件,但是文件路徑包含空格,並且以某種方式我無法使其正常工作。 我檢查了許多其他SO帖子並實現了解決方案,例如帶有轉義引號的環繞代碼並將其拆分為命令和參數等。我的代碼如下:
try {
ProcessBuilder pBuilder = new ProcessBuilder(
// Main Command.
"C:\\namewith space\\database\\postgres_db\\bin\\pg_ctl.exe",
// Command Parameters.
"start",
"-D C:\\namewith space\\database\\database",
/*The quotes in the next argument are necessary, the -o stands for 'options' and everything between the quotes are the actual database parameters which to start the Database with.*/
"-o \"-p 15000\"",
"-l C:\\namewith space\\database\\postgres_db\\bin\\postgres_log.txt");
File log = new File("\"C:\\folder\\log.txt\"");
pBuilder.redirectErrorStream(true);
pBuilder.redirectOutput(Redirect.appendTo(log));
Process p = pBuilder.start();
} catch (IOException ex) {
System.out.println("Exception Occurred: " + ex);
}
到目前為止,我已經嘗試過:
Runtime.getRuntime().exec("full command with/without any/all escaped quotes");
方法,但是在SO上搜索時,我發現每個人都在說您應該使用ProcessBuilder。 "\\"C:\\\\namewith space\\\\database\\\\postgres_db\\\\bin\\\\pg_ctl.exe\\" start"
我一直得到的錯誤(通過System.out.println("Exception Occurred: " + ex);
)是: java.io.IOException:無法運行程序“ C:\\ name with space \\ database \\ postgres_db \\ bin \\ pg_ctl。 exe” :文件名,目錄名稱或卷標簽語法不正確。
如果您需要任何額外的零件/代碼,請告訴我,我會盡力提供詳細信息。
嘗試解決問題。
首先,只需將IOException中顯示的絕對路徑讀入File對象,然后調用exist()方法以檢查該文件確實存在,並且JVM可以訪問它。
如果這樣不起作用,請修復您的路徑或訪問權限。 如果文件確實存在,並且您可以訪問它,則創建不帶任何參數的ProcessBuilder,只需使用exe的絕對路徑即可。
您現在不應該獲取IOException。 然后一一添加參數 。 如果您發現一個損壞的東西,請修復該參數(也許雙引號丟失),然后繼續執行下一個直到完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.