从Java运行Unix命令非常简单.
Runtime.getRuntime().exec(myCommand);
但是可以从Java代码运行Unix shell脚本吗?如果是,从Java代码中运行shell脚本是一个好习惯吗?
您应该真正关注Process Builder.它真的是为这种东西而建的.
ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2"); Mapenv = pb.environment(); env.put("VAR1", "myValue"); env.remove("OTHERVAR"); env.put("VAR2", env.get("VAR1") + "suffix"); pb.directory(new File("myDir")); Process p = pb.start();
我想说从Java运行shell脚本不符合Java的精神.Java意味着是跨平台的,运行shell脚本会将其使用限制在UNIX.
话虽如此,绝对可以从Java中运行shell脚本.您使用的是与您列出的完全相同的语法(我自己没有尝试过,但是尝试直接执行shell脚本,如果不起作用,请执行shell本身,将脚本作为命令行参数传递) .
我想你已回答了自己的问题
Runtime.getRuntime().exec(myShellScript);
至于它是否是一个好习惯......你想用一个你不能用Java做的shell脚本做什么?
您也可以使用Apache Commons exec库.
示例:
package testShellScript; import java.io.IOException; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteException; public class TestScript { int iExitValue; String sCommandString; public void runScript(String command){ sCommandString = command; CommandLine oCmdLine = CommandLine.parse(sCommandString); DefaultExecutor oDefaultExecutor = new DefaultExecutor(); oDefaultExecutor.setExitValue(0); try { iExitValue = oDefaultExecutor.execute(oCmdLine); } catch (ExecuteException e) { System.err.println("Execution failed."); e.printStackTrace(); } catch (IOException e) { System.err.println("permission denied."); e.printStackTrace(); } } public static void main(String args[]){ TestScript testScript = new TestScript(); testScript.runScript("sh /root/Desktop/testScript.sh"); } }
为了进一步参考,还给出了Apache Doc的一个例子.
是的,有可能这样做.这对我有用.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.omg.CORBA.portable.InputStream; public static void readBashScript() { try { Process proc = Runtime.getRuntime().exec("/home/destino/workspace/JavaProject/listing.sh /"); //Whatever you want to execute BufferedReader read = new BufferedReader(new InputStreamReader( proc.getInputStream())); try { proc.waitFor(); } catch (InterruptedException e) { System.out.println(e.getMessage()); } while (read.ready()) { System.out.println(read.readLine()); } } catch (IOException e) { System.out.println(e.getMessage()); } }