2017-05-15 36 views
0

如何通过java代码调用shell脚本? 我写下了下面的代码。 我得到的进程退出代码为127. 但似乎我的UNIX机器上的shell脚本从未被调用过。从java获取错误

String scriptName = "/xyz/downloads/Report/Mail.sh"; 
String[] commands = {scriptName,emailid,subject,body}; 
Runtime rt = Runtime.getRuntime(); 
Process process = null; 
try{ 
    process = rt.exec(commands); 
    process.waitFor(); 
    int x = process.exitValue(); 
    System.out.println("exitCode "+x); 
}catch(Exception e){ 
    e.printStackTrace(); 
} 
+0

是脚本可执行+ X? –

+0

是的,我已经给了chmod 777 – chandan

回答

0

从这个帖子在这里127 Return code from $?

你得到的错误代码,如果命令不在路径中找到或文字没有+ X模式。 你可以有下面的代码打印出精确的输出

BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); 
     String s= null; 
     while ((s = stdInput.readLine()) != null) { 
       System.out.println(s); 
      } 

BufferedReader stdOut = new BufferedReader(new InputStreamReader(process. getErrorStream())); 
     String s= null; 
     while ((s = stdOut.readLine()) != null) { 
       System.out.println(s); 
      } 
0

如果您收到的退出代码,那么你的脚本执行。有一个命令在“Mail.sh”中运行,它不会被成功执行并返回状态码127.
可能有一些路径在shell中显式设置,但不可用于脚本,当在shell外执行时。如果你能在一个shell终端上运行/xyz/downloads/Report/Mail.sh 尝试......

  • 检查。如果有任何问题,请修正错误。
  • 如果在终端中运行此命令时没有错误,则尝试在java程序中使用shell运行该命令。 String[] commands = {"/bin/sh", "-c", scriptName,emailid,subject,body};
    (检查@约翰Muiruri的答案让你的命令的完整输出,你可以清楚地看到你的脚本失败,如果您添加的这些代码行)