[英]How to execute a interactive shell script using java Runtime?
我想知道有沒有辦法執行以下shell腳本,它等待使用java的Runtime類的用戶輸入?
#!/bin/bash
echo "Please enter your name:"
read name
echo "Welcome $name"
我使用以下java代碼來執行此任務,但它只顯示空白控制台。
public class TestShellScript {
public static void main(String[] args) {
File wd = new File("/mnt/client/");
System.out.println("Working Directory: " +wd);
Process proc = null;
try {
proc = Runtime.getRuntime().exec("sudo ./test.sh", null, wd);
} catch (Exception e) {
e.printStackTrace();
}
}
}
事情就是當我執行上面的程序時,我相信它將執行一個shell腳本,而shell腳本將等待用戶輸入,但它只是打印當前目錄然后退出。 有沒有辦法做到這一點,或者根本不可能在java中?
提前致謝
它打印當前目錄和退出的原因是因為您的Java應用程序退出。 您需要向創建的進程的輸入和錯誤流添加(線程)偵聽器,並且您可能希望將printStream添加到進程的輸出流
例:
proc = Runtime.getRuntime().exec(cmds);
PrintStream pw = new PrintStream(proc.getOutputStream());
FetcherListener fl = new FetcherListener() {
@Override
public void fetchedMore(byte[] buf, int start, int end) {
textOut.println(new String(buf, start, end - start));
}
@Override
public void fetchedAll(byte[] buf) {
}
};
IOUtils.loadDataASync(proc.getInputStream(), fl);
IOUtils.loadDataASync(proc.getErrorStream(), fl);
String home = System.getProperty("user.home");
//System.out.println("home: " + home);
String profile = IOUtils.loadTextFile(new File(home + "/.profile"));
pw.println(profile);
pw.flush();
要運行它,您需要下載我的sourceforge項目: http : //tus.sourceforge.net/但希望代碼片段足夠有用,您可以適應J2SE以及您正在使用的任何其他內容。
如果您使用Java ProcessBuilder,您應該能夠獲得您創建的Process的輸入,錯誤和輸出流。
這些流可用於獲取流程中的信息(如輸入提示),但也可以編寫它們以直接將信息輸入流程。 例如:
InputStream stdout = process.getInputStream ();
BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
String line;
while(true){
line = reader.readLine();
//...
那將直接從過程中獲得輸出。 我自己沒有這樣做,但我很確定process.getOutputStream()
為您提供了一些可以直接寫入以將輸入發送到進程的東西。
從Runtime.exec
運行交互式程序(如sudo
的問題在於它將stdin和stdout附加到管道而不是它們所需的控制台設備。 您可以通過將輸入和輸出重定向到/dev/tty
來使其工作。
您可以實現使用新的相同的行為ProcessBuilder
類,設置使用重定向ProcessBuilder.Redirect.INHERIT
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.