使用Runtime.getRuntime()。exec()執(zhí)行Java文件
首先,您的命令行看起來(lái)不正確。執(zhí)行命令與批處理文件不同,它不會(huì)執(zhí)行一系列命令,而只會(huì)執(zhí)行一個(gè)命令。
從外觀上看,您正在嘗試更改要執(zhí)行的命令的工作目錄。一個(gè)更簡(jiǎn)單的解決方案是使用ProcessBuilder,它將允許您指定給定命令的起始目錄…
例如…
try { ProcessBuilder pb = new ProcessBuilder('java.exe', 'testfile'); pb.directory(new File('C:Userssg552Desktop')); pb.redirectError(); Process p = pb.start(); InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream()); consumer.start(); p.waitFor(); consumer.join();} catch (IOException | InterruptedException ex) { ex.printstacktrace();}//...public class InputStreamConsumer extends Thread { private InputStream is; private IOException exp; public InputStreamConsumer(InputStream is) {this.is = is; } @Override public void run() {int in = -1;try { while ((in = is.read()) != -1) {System.out.println((char)in); }} catch (IOException ex) { ex.printstacktrace(); exp = ex;} } public IOException getException() {return exp; }}
ProcessBuilder 還可以更輕松地處理可能在其中包含空格的命令,而不必將引號(hào)引起來(lái)。
解決方法此代碼將執(zhí)行一個(gè)外部exe應(yīng)用程序。
private void clientDataActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: try { Runtime.getRuntime().exec('C:Program Files (x86)VideoLANVLCvlc.exe'); } catch(Exception e) {System.out.println(e.getMessage()); } }
如果我想執(zhí)行外部Java文件怎么辦?可能嗎?例如以下命令:
Runtime.getRuntime().exec('cmd.exe /C start cd 'C:Userssg552Desktop java testfile');
該代碼在java和cmd提示符下不起作用。如何解決呢?
相關(guān)文章:
1. android - weex 項(xiàng)目createInstanceReferenceError: Vue is not defined2. PHPExcel表格導(dǎo)入數(shù)據(jù)庫(kù)怎么導(dǎo)入3. android - 哪位大神知道java后臺(tái)的api接口的對(duì)象傳到前端后輸入日期報(bào)錯(cuò),是什么情況?求大神指點(diǎn)4. javascript - 如圖,百度首頁(yè),查看源代碼為什么什么都沒有?5. pdo 寫入到數(shù)據(jù)庫(kù)的內(nèi)容為中文的時(shí)候?qū)懭雭y碼6. vue2.0+webpack 如何使用bootstrap?7. PHP類封裝的插入數(shù)據(jù),總是插入不成功,返回false;8. docker綁定了nginx端口 外部訪問不到9. html - 根據(jù)用戶id實(shí)現(xiàn)論壇用戶頭像顯示的最佳實(shí)現(xiàn)10. mac連接阿里云docker集群,已經(jīng)卡了2天了,求問?
