2013-12-20 34 views
2

單擊jsp頁面中的按鈕時,我想運行批處理文件。我編寫了這個代碼來執行一個方法內的批處理文件,但它不起作用。 Plz幫助我。如何從Java代碼運行批處理文件點擊按鈕

public String scheduler() { 
    String result=SUCCESS; 
    try { 

     Process p = Runtime.getRuntime().exec("cmd /c start.bat", null, new File("C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\start")); 

     System.out.println("manual scheduler for application.."+p); 
    } catch(Exception e) { 
    } 
} 
+0

define - not working –

回答

0

this,下面的代碼應該工作(只是刪除cmd /c):

public String scheduler() { 
    String result=SUCCESS; 
    try { 

     File f = new File("C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\start") 
     Process p = Runtime.getRuntime().exec("start.bat", null, f); 

     System.out.println("manual scheduler for application.."+p); 
    } catch(Exception e) { 
    } 
} 
+0

hi mvieghofer thanx for reply .. but this sol is not working。 Runtime.getRuntime()。exec(「cmd/c start scheduler1.bat」)正在運行。但默認情況下,cmd將採用weblogic批處理文件存儲的路徑。我通過代碼發送的路徑地址不起作用。 –

+0

cmd採取默認地址E:\ bea \ user_projects \ domain \ base_domain.which是startWeblogic批處理文件地址.i認爲應用程序正在服務器上運行這就是爲什麼它採取服務器批處理文件的默認地址...困惑。 –

1

添加該代碼,

batFile.setExecutable(true); 

//Running bat file 
Process exec = Runtime.getRuntime().exec(PATH_OF_PARENT_FOLDER_OF_BAT_SCRIPT_FILE+File.separator+batFile.getName());                
byte []buf = new byte[300]; 
InputStream errorStream = exec.getErrorStream(); 
errorStream.read(buf);        
logger.debug(new String(buf)); 
int waitFor = exec.waitFor(); 
if(waitFor==0) { 
    System.out.println("BAT script executed properly"); 
} 
+0

@Surya Rawat考慮[接受答案](http://meta.stackexchange.com/a/5235/245346)如果它解決您的查詢。 – Aditya

0

目前尚不清楚,在這裏,你是否只是想運行一個bat文件或者你想等待它運行。

// bat文件所在的位置是必需的,例如。 K:/MyPath/MyBat.bat在我的情況 //如果bat文件是在類路徑中,那麼你可以提供直接的bat文件名MyBat.bat

**Runtime rt = Runtime.getRuntime() ; 
Process batRunningProcess= rt.exec("cmd /c K:/MyPath/MyBat.bat");** 

//這是等待的過程來完成 //如果過程完成,然後值爲0

**final int exitVal = lawTab_Indexer.waitFor();** 

//如果你只是想運行一個批處理文件,並不想等待它完成獲得這行不是必需的。

+0

我想從struts 2應用程序運行批處理文件,onclicking提交option.onclicking提交我調用上面給出的方法,但功能不工作。 –