如何从Java代码运行Unix shell脚本? [英] How to run Unix shell script from Java code?
本文介绍了如何从Java代码运行Unix shell脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从Java运行Unix命令非常简单。
It is quite simple to run a Unix command from Java.
Runtime.getRuntime().exec(myCommand);
但是可以从Java代码运行Unix shell脚本吗?如果是,从Java代码中运行shell脚本是一个好习惯吗?
But is it possible to run a Unix shell script from Java code? If yes, would it be a good practice to run a shell script from within Java code?
推荐答案
你应该看看< a href =http://docs.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html =noreferrer> Process Builder 。它真的是为这种东西而构建的。
You should really look at Process Builder. It is really built for this kind of thing.
ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
Map<String, String> env = 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代码运行Unix shell脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文