我创建了一个Spring Boot项目,该项目在本地tomcat上运行(我打算将其部署到Web服务器上)。在该项目中,我创建了一个REST服务,该服务应执行一个.bat文件。
我的休息服务看起来像这样(都不起作用)
@RequestMapping(value = "/esc", method= RequestMethod.GET)
public String esc() throws IOException, InterruptedException {
String folder = "P:\\Documents\\testcmd";
String[] cmdarray = new String[]{"cmd -c","dosomething.cmd"};
ProcessBuilder processBuilder = new ProcessBuilder( cmdarray );
processBuilder.directory(new File(folder));
Process process = processBuilder.start();
int exitCode = -1;
boolean finished = false;
while ( !finished ) {
exitCode = process.waitFor();
finished = true;
}
return folder;
}
@RequestMapping(value = "/ex", method= RequestMethod.GET)
public String executeShellScript(){
//final String shCmd = "/bin/bash -c helloworld.sh";
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
final String shCmd = "cmd -c P:/Documents/testcmd/dosomething.cmd";
String output = executeCommand(shCmd);
return output;
}
private String executeCommand(String command){
Process p;
InputStream in = null;
String value = "";
try {
p = Runtime.getRuntime().exec(command);
in = p.getInputStream();
int ch;
while((ch = in.read()) != -1) {
value = String.valueOf((char)ch);
}
}catch (IOException e){
e.printStackTrace();
}
return value;
}
我在processbuilder和运行时中尝试过。 我要执行的文件在此文件夹中:“ P:\ Documents \ testcmd”
是否甚至可以使用tomcat服务器执行本地文件?
答案 0 :(得分:1)
我解决了这个问题。使用Runtime.getRuntime().exec(command)
的解决方案是正确的。只有我的系统调用是错误的。我不得不使用final String shCmd = "cmd -c P:/Documents/testcmd/dosomething.cmd";
而不是"P:/Documents/testcmd/dosomething.cmd"
。另外,我还必须更改dosomething.cmd
,因为它是错误的。当执行普通的Java代码时,该文件将打开一个cmd终端,然后在一个无限循环中打印问候。我更改了文件内容,而不是在终端中无休止地循环,它将向所有文件打印问候。
// method is mapped on root/ex
@RequestMapping(value = "/ex", method= RequestMethod.GET)
public String executeShellScript(){
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
final String shCmd = "P:\\Documents\\testcmd\\dosomething.cmd -c";
String output = executeCommand(shCmd);
return output;
}
之前和之后的批处理文件
@echo off
:start
echo hallo
pause
goto start
之后
@echo off
@echo This is a test>> P:/Documents/testcmd/file.txt
@echo 123>> P:/Documents/testcmd/file.txt
@echo 245.67>> P:/Documents/testcmd/file.txt