如何使用java Runtime执行交互式shell脚本?

Rah*_*kar 6 java runtime.exec

我想知道有没有办法执行以下shell脚本,它等待使用java的Runtime类的用户输入?

#!/bin/bash

echo "Please enter your name:"
read name
echo "Welcome $name"
Run Code Online (Sandbox Code Playgroud)

我使用以下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();
             }


}
Run Code Online (Sandbox Code Playgroud)

}

事情就是当我执行上面的程序时,我相信它将执行一个shell脚本,而shell脚本将等待用户输入,但它只是打印当前目录然后退出.有没有办法做到这一点,或者根本不可能在java中?

提前致谢

Con*_*Del 1

它打印当前目录并退出的原因是因为您的 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();
Run Code Online (Sandbox Code Playgroud)

要运行它,您需要下载我的 sourceforge 项目:http://tus.sourceforge.net/但希望代码片段具有足够的指导意义,以便您可以适应 J2SE 以及您正在使用的任何其他内容。