我想从我的程序运行一个shell脚本,但它似乎没有做任何事情.我在linux终端直接运行相同的命令,它工作正常,所以我猜它是我的java代码.正如您所看到的,我首先使用PrintWriter将命令写入shell脚本,但我希望这不会影响shell脚本本身的运行.任何帮助,将不胜感激!
public static void main(String[] args) {
// TODO Auto-generated method stub
String nfdump = "nfdump -o csv -r /home/shane/Documents/nfdump/nfcapd.201211211526>blank.txt";
try {
FileWriter fw = new FileWriter("/home/shane/Documents/script.sh");
PrintWriter pw = new PrintWriter(fw);
pw.println("#!/bin/bash");
pw.println(nfdump);
pw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Process proc = null;
try {
proc = Runtime.getRuntime().exec("sh /home/shane/Documents/script.sh");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
rep*_*mer 28
您应该使用返回Process来获得结果.
Runtime#exec作为单独的进程执行命令并返回类型的对象Process.您应该调用,Process#waitFor以便程序等待新进程完成.然后,您可以调用Process.html#getOutputStream()返回的Process对象以检查已执行命令的输出.
创建流程的另一种方法是使用ProcessBuilder.
Process p = new ProcessBuilder("myCommand", "myArg").start();
Run Code Online (Sandbox Code Playgroud)
使用a ProcessBuilder,可以将命令的参数列为单独的参数.
见的ProcessBuilder和的Runtime.exec()之间的区别和的ProcessBuilder VS的Runtime.exec()更多地了解之间的差异Runtime#exec和ProcessBuilder#start.
试试这个,它会起作用.
String[] cmd = new String[]{"/bin/sh", "path/to/script.sh"};
Process pr = Runtime.getRuntime().exec(cmd);
Run Code Online (Sandbox Code Playgroud)
当您从Java执行脚本时,它会生成一个新的shell,其中未设置PATH环境变量。
使用以下代码设置PATH env变量将运行您的脚本。
String[] env = {"PATH=/bin:/usr/bin/"};
String cmd = "you complete shell command"; //e.g test.sh -dparam1 -oout.txt
Process process = Runtime.getRuntime().exec(cmd, env);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69554 次 |
| 最近记录: |