[英]How to Run a Batch File from Java Code onclicking a Button
On clicking a button in a jsp page, I want to run a batch file. 单击jsp页面中的按钮时,我要运行批处理文件。 I wrote this code to execute a batch file inside a method, but it's not working.
我写了这段代码来执行方法中的批处理文件,但是它不起作用。 Plz help me out.
请帮我。
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) {
}
}
Add this code, 添加此代码,
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");
}
According to this , the following code should work (just remove the cmd /c
): 根据此 ,下面的代码应该工作(只是删除
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) {
}
}
It's not clear here whether you just want to run a bat file or you want to wait for it to run. 这里尚不清楚您是只想运行bat文件还是要等待它运行。
// the location where bat file is located is required eg. //需要bat文件所在的位置,例如 K:/MyPath/MyBat.bat in my case // If bat file is in classpath then you can provide direct bat file name MyBat.bat
K:/MyPath/MyBat.bat在我的情况下//如果bat文件位于类路径中,则可以提供直接的bat文件名MyBat.bat
**Runtime rt = Runtime.getRuntime() ;
Process batRunningProcess= rt.exec("cmd /c K:/MyPath/MyBat.bat");**
// This is to wait for process to complete //if process is completed then value will be 0 //这是等待过程完成// //如果过程完成,则值将为0
**final int exitVal = lawTab_Indexer.waitFor();**
// This line is not required if you just want to run a bat file and dont want to wait for it to get completed. //如果您只想运行bat文件并且不想等待它完成,则不需要此行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.