[英]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.