我正在尝试从Java类调用shell脚本,并且我希望将shell脚本的输出存储在日志文件中。
我的代码看起来像这样
String cmd = "/bin/sh /ws/priyapan-rcd/US248547/label_update.sh "+ branch_name + " "
+ product_type + " "
+ new_branch_name + " "
+ new_branch_label;
System.out.println("cmd is" +cmd);
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmd);
try {
p.waitFor();
} catch (Exception e) {
logger.error("{}", e);
}
//Gets the exit status to determine if label update was successful.
exitValue = p.exitValue();
// Sleeping for 500 milliseconds to give the script enough time to create the log files
Thread.sleep(500);
System.out.println("about to create the log file");
File LabelUpdateLog = new File("/ws/priyapan-rcd/workspace/labelupdate_"+train_id+".log");
//File LabelUpdateLog = new File("/users/ccmbuild/deactivation_cerebro/LabelUpdate_"+train_id+".log");
System.out.println("log file created");
logger.debug("{}", LabelUpdateLog);
所有打印语句都被执行但未生成日志文件。 任何人都可以建议原因
我认为我的课程中没有调用此脚本/ws/priyapan-rcd/US248547/label_update.sh 任何想法为什么?有人请建议
答案 0 :(得分:1)
您可以将代码保留为只需更改命令,如
String cmd = "/bin/sh /ws/priyapan-rcd/US248547/label_update.sh "+ branch_name + " "
+ product_type + " "
+ new_branch_name + " "
+ new_branch_label +" >> LogFile.log";
如果要在相对路径上创建文件,请相应地更改命令。
String cmd = "/bin/sh /ws/priyapan-rcd/US248547/label_update.sh "+ branch_name + " "
+ product_type + " "
+ new_branch_name + " "
+ new_branch_label +" >> /ws/priyapan-rcd/workspace/labelupdate_"+train_id+".log";
答案 1 :(得分:0)
两件主要的事情:
labelUpdateLog.createFile()
顺便说一下,Javadoc of ProcessBuilder中的示例只是说明了如何执行命令并将输出保存到日志文件中。
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.directory(new File("myDir"));
File log = new File("log");
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.appendTo(log));
Process p = pb.start();