2016-12-03 164 views
1

我必須在Java中執行以下Windows的cmd命令。如何在Java中更改目錄並執行文件

cmd命令:

Microsoft Windows [Version 6.1.7600] 
Copyright (c) 2009 Microsoft Corporation. All rights reserved. 

//First i have to change my default directory// 

C:\Users\shubh>D: 

//Then move to a specific folder in the D drive.// 

D:\>cd MapForceServer2017\bin\ 

//then execute the .mfx file from there. 

D:\MapForceServer2017\bin>mapforceserver run C:\Users\shubh\Desktop\test1.mfx 

執行

Output files: 
library: C:\Users\shubh\Documents\Altova\MapForce2017\MapForceExamples\Tutorial\library.xml 
Execution successful. 
+1

你爲什麼不嘗試在Windows的.bat腳本?只是一個想法! – harshavmb

+0

我希望在我的servlet文件中添加上述命令的java代碼,用戶將上傳文件,然後它將被mapforceserver run命令使用。因此,每次用戶上傳新文件時,文件名都會更改。我們可以在運行期間動態更改批處理文件的內容嗎? – shubham0001

+1

是的,你可以使用java.io.File API編寫,通過下面的鏈接。 http://stackoverflow.com/questions/29820079/write-into-bat-file-with-java – harshavmb

回答

2

我建議使用https://commons.apache.org/proper/commons-exec/用於Java內部從執行O/S命令,因爲它有各種問題的交易結果你稍後可能會遇到。

您可以使用:

CommandLine cmdLine = CommandLine.parse("cmd /c d: && cd MapForceServer2017\\bin\\ && mapforceserver run ..."); 
DefaultExecutor executor = new DefaultExecutor(); 
int exitValue = executor.execute(cmdLine); 
+2

+1使用'&&'並使用第三方庫來處理子流程。順便提一下,您可以用'cd/d D:\\ MapForceServer ...'替換'd:&& cd MapForceServer ...':'/ d'開關允許您同時更改驅動器和目錄。 –

+0

感謝cherouivm對你的回答以及Luke Woodward的評論。基本上我所做的就是使用兩種創建批處理文件(由harshavmb建議的方法)的方法的組合,它具有多個命令並且使用cherouvim的方法使用commandline.parse()函數用字符串變量調用該批處理文件,該變量將變量的值(基本上是用戶上傳的文件名)發送到批處理文件以供進一步執行。 – shubham0001

+0

@ shubham0001創建一個批處理文件看起來像是一種矯枉過正的情況,以防萬一你需要執行的命令總數不是那麼多。你可以用'&&'連接它們。 – cherouvim

0

我有些同樣的要求,一段時間回來,當時我從堆下面的代碼片段,我認爲。嘗試這個。

String[] command = 
    { 
     "cmd", 
    }; 
    Process p = Runtime.getRuntime().exec(command); 
    new Thread(new SyncPipe(p.getErrorStream(), System.err)).start(); 
    new Thread(new SyncPipe(p.getInputStream(), System.out)).start(); 
    PrintWriter stdin = new PrintWriter(p.getOutputStream()); 
    stdin.println("dir c:\\ /A /Q"); 
    // write any other commands you want here 
    stdin.close(); 
    int returnCode = p.waitFor(); 
    System.out.println("Return code = " + returnCode); 

SyncPipe類:

class SyncPipe implements Runnable 
{ 
public SyncPipe(InputStream istrm, OutputStream ostrm) { 
     istrm_ = istrm; 
     ostrm_ = ostrm; 
    } 
    public void run() { 
     try 
     { 
      final byte[] buffer = new byte[1024]; 
      for (int length = 0; (length = istrm_.read(buffer)) != -1;) 
      { 
       ostrm_.write(buffer, 0, length); 
      } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 
    private final OutputStream ostrm_; 
    private final InputStream istrm_; 
} 
相關問題