我正在编写一个java程序,它在某些时候执行cmd文件。 两者都在同一目录中。
我正在使用ProcessBuilder,因为它更灵活。 但是,当我运行此代码时,它失败了:
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");
我得到了这个例外:
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
然而,当我评论这些行而不是它的作用时:
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");
我需要这些行,因为我想要有日志消息。
答案 0 :(得分:0)
我发现了我的错误......这是一个愚蠢的错误。这段代码实际上有效:
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");
问题在于这一行:
File log = new File("log.txt");
在我的生产环境中,它是一条很长的路径(这是错误的),但为了演示目的,我在此处发布问题之前更改了它。我认为这个问题与cmd文件有关,异常告诉我整个时间......现在我给了一个正确的日志文件路径后就可以运行了..大家都是