Reputation: 19
I created a spring boot project, which I'm running on a local tomcat (I'm planning to deploy this to a webserver). Within this project I created a rest-service, which should execute a .bat file.
my rest services look like this (neither of them works)
@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;
}
I tried it with a processbuilder and with runtime. The file I want to execute is in this folder: "P:\Documents\testcmd"
Is it even possible to execute a local file with a tomcat server?
Upvotes: 0
Views: 635
Reputation: 19
I solved the problem. The sollution with Runtime.getRuntime().exec(command)
was correct. Only my system call was wrong. Instead of final String shCmd = "cmd -c P:/Documents/testcmd/dosomething.cmd";
I had to use "P:/Documents/testcmd/dosomething.cmd"
. In addition I had to change the dosomething.cmd
because it was wrong. When executing the plain java code, the file would open a cmd terminal and then print hello in an endless loop. I changed the file content that instead of the endless loop in the terminal it prints hello into another file.
// 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;
}
batch file before & after
@echo off
:start
echo hallo
pause
goto start
after
@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
Upvotes: 1