I am writing a java program which executes a cmd-file at some point. Both are in the same directory.
I am using the ProcessBuilder, since it is more flexible. However when I run this code it fails:
String current_directory = System.getProperty("user.dir");
ProcessBuilder builder=new ProcessBuilder(current_directory+"\\"+ "myCmdFile.cmd");
builder.directory(new File(current_directory));
File log = new File("log.txt");
builder.redirectErrorStream(true);
builder.redirectOutput(Redirect.appendTo(log));
Process process=builder.start();
process.waitFor();
System.out.println("CMD file executed");
I get this exception:
java.io.IOException: Cannot run program "C:\test\myCmdFile.cmd" (in directory "C:\test"): No such file or directory
at java.lang.ProcessBuilder.start(Unknown Source)
at org.java.test.executeCmdFile(MyMainClass.java:189)
at org.java.test.main(MyMainClass.java:70)
Caused by: java.io.IOException: No such file or directory
at java.lang.ProcessImpl.openForAtomicAppend(Native Method)
at java.lang.ProcessImpl.newFileOutputStream(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 3 more
However, when I comment out these lines than it works:
ProcessBuilder builder=new ProcessBuilder(current_directory+"\\"+
"myCmdFile.cmd");
//builder.directory(new File(current_directory));
//File log = new File("log.txt");
// builder.redirectErrorStream(true);
// builder.redirectOutput(Redirect.appendTo(log));
Process process=builder.start();
process.waitFor();
System.out.println("CMD file executed");
I need these lines, since I want to have log messages.
I found my error...it was a stupid one..This code actually works:
String current_directory = System.getProperty("user.dir");
ProcessBuilder builder=new ProcessBuilder(current_directory+"\\"+ "myCmdFile.cmd");
builder.directory(new File(current_directory));
File log = new File("log.txt");
builder.redirectErrorStream(true);
builder.redirectOutput(Redirect.appendTo(log));
Process process=builder.start();
process.waitFor();
System.out.println("CMD file executed");
The problem was this line:
File log = new File("log.txt");
In my production environment it was a long path (which was wrong), however for demonstration purposes I changed it, before I posted the question here. I thought that the problem was connected with the cmd-file the exception told me that the whole time...now after i gave a correct path for the log-file it works..thx everyone