try {
try {
String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
Runtime r = Runtime.getRuntime();
Process p = r.exec(command);
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Error" +"Execution!","Error",JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
Logger.getLogger(DBBackUp.class.getName()).log(Level.SEVERE, null, ex);
}
当我运行此代码时,我只得到命令提示符。 .bat文件未运行。 如何使用此代码执行批处理文件?
先谢谢
答案 0 :(得分:2)
考虑 使用Apache Commons Exec。
答案 1 :(得分:1)
让你的" test.bat"是这样的:
dir
pause
然后您可以按如下方式执行此批处理文件:
try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("rundll32 url.dll,FileProtocolHandler " + "D:\\test.bat");
p.waitFor();
}catch(Exception ex){ex.printStackTrace();}
答案 2 :(得分:1)
您可以尝试这样的事情:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class BatchExecuteService {
public static void main(String[] args) {
BatchExecuteService batchExecuteService = new BatchExecuteService();
batchExecuteService.run();
}
public void run() {
try {
String cmds[] = {"D:\\test.bat"};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmds);
process.getOutputStream().close();
InputStream inputStream = process.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
BufferedReader bufferedrReader = new BufferedReader(inputstreamreader);
String strLine = "";
while ((strLine = bufferedrReader.readLine()) != null) {
System.out.println(strLine);
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}