[英]Java Linux Shell Application
因此,我刚收到一个创建Java Shell App的任务,无需使用任何第三方库,也无需使用Runtime.exec()或ProcessBuilder API。
我不需要解决方案(显然我想自己做),但是我确实需要提示如何执行此操作? 我希望该应用程序打开一个shell提示符,该提示符将接受使用JDK 8(Nashorn?)的各种命令。
谢谢!
不清楚要实现的目标。 如果要运行Nashhorn Shell,则可以这样实现(Java 8)
import jdk.nashorn.tools.Shell;
public class NashornShell {
public static void main(String[] args) {
Shell.main(new String[]{ "-scripting"});
}
}
当您看到Nashorn提示符jjs>
,可以执行Linux命令...
jjs> $EXEC("ls");
它将列出当前目录(使用Linux ls
命令)。
...或执行Java命令...
jjs> java.lang.System.out.println("foo");
...或执行JavaScript命令...
jjs> print("foo");
有关更多信息,请参阅nashorn指南 。
编辑如果只想传递yourCommand
作为参数。
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(new String[]{"-scripting"});
String yourCommand = "ls";
Object eval = engine.eval("$EXEC(\"" + yourCommand + "\")");
System.out.println(eval);
编辑 do you think that instead of Nashorn I could just use raw streams directed to the OS from JVM
以下是可能的
Commands.java
class Commands {
public static void main(String[] args) {
System.out.println("ls");
System.out.println("whoami");
}
}
运行
#!/bin/sh
java Commands | while read command; do
echo
echo "command: $command"
$command
done
但这显然不建议您在execute
Commands
的输出时使用:
无论您要做什么,使用nashorn内部类(如jdk.nashorn.tools.Shell)都不是一个好主意。 在Java 9中,此软件包不是jdk.scripting.nashorn模块的导出软件包。 因此,使用Java 9,您将遇到程序包访问失败的情况(即使没有安全管理器,因为模块的读/导出访问检查更像是类的成员访问检查)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.