我試圖從Java程序運行批處理文件。 例如:我在「Program Files」文件夾中有一個批處理「abc.bat」。如何使用Java中的命令提示符訪問文件路徑
我想從我的Java程序執行此批處理。我使用的是CommandLine類,Commons-exec jar。
CommandLine cmdLine = CommandLine.parse("cmd");
cmdLine.addArgument("/c start \"\" \"C:\\Program Files\\abc.bat\"");
DefaultExecutor exec = new DefaultExecutor();
Process p = Runtime.getRuntime().exec(cmdLine.toString());
exec.execute(cmdLine);
上面的代碼拋出一個錯誤說的「Windows無法找到該文件。請確保您正確,鍵入名稱,然後再試一次」。而且,這是因爲路徑中的空間。
所以,我嘗試了@ brso05提供的答案,並且工作正常。但我希望它成爲未來階層。請在下面找到我的代碼並幫我修復它。
final CommandLine cmdLine = CommandLine.parse("cmd.exe");
cmdLine.addArgument("/c");
cmdLine.addArgument("start");
cmdLine.addArgument("\""+ batchFileExecute.getParent().toString() + "\"");
ExecutorService es = Executors.newFixedThreadPool(1);
Future<?> future = es.submit(new Runnable() {
public void run() {
DefaultExecutor exec = new DefaultExecutor();
try {
Process p = Runtime.getRuntime().exec(cmdLine.toString());
exec.execute(cmdLine);
System.out.println(p.waitFor());
}
catch (IOException e)
{
e.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
String thread_status = null;
try
{
thread_status = future.get().toString();
System.out.println(thread_status+" completed the execution");
}
catch (NullPointerException e)
{
System.out.println("The execution of the received project is complete.");
// In here I want to do some processing again.
}
我提到的代碼工作,但它不工作,如果我的批處理文件在路徑中有空格。你能幫我解決這個問題嗎?
因爲你已經給出了作品的片段,但後來我不能把它放到未來。它不以所需的方式工作。
在此先感謝!
它應該工作,你確定該文件在那裏? – brso05 2014-11-25 14:32:30
是的..我試過..和它不工作..我試圖通過命令提示符從Java運行批處理.. – user1395264 2014-11-25 14:52:30
試試我的回答我認爲它會爲你工作... – brso05 2014-11-25 14:58:13