【问题标题】:Write and read data from console at run time in java program在 java 程序中运行时从控制台写入和读取数据
【发布时间】:2017-04-13 00:20:34
【问题描述】:

我有一个带有一些命令的 shell 脚本,其中一个命令期望在运行时输入一些数据。我正在使用 exec() 方法运行这个 shell 脚本。目前,如果要求输入,我正在手动输入数据。以下是我的代码,

            Process p = Runtime.getRuntime().exec("myshellscript");

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

           // read any errors from the attempted command
            System.out.println("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }

            System.exit(0);

我想要做的是每当控制台期望的数据被输入时,它应该由java程序输入,然后继续我的进一步的java程序。

【问题讨论】:

    标签: java shell console command processbuilder


    【解决方案1】:

    这是我的工作:

    1. 创建两个将从 p.getInputStream() 和 p.getErrorStream() 读取的线程,
    2. 将数据写入p.getOutputStream(),
    3. 等待两个线程终止(使用 join() 方法)

    编辑:

    public class Main {
        private static final Logger LOG = Logger.getLogger(Main.class.getName());
    
        public static void main(String[] args) {
            try {
                Process p = Runtime.getRuntime().exec("myshellscript");
                Thread outHandler = new OutputHandler(p.getInputStream(), "UTF-8");
                outHandler.setDaemon(true);
                outHandler.start();
                Thread errHandler = new OutputHandler(p.getErrorStream(), "UTF-8");
                errHandler.setDaemon(true);
                errHandler.start();
                sendInput(p, "the input data", "UTF-8");
                int result = p.waitFor();
                outHandler.join();
                errHandler.join();
                System.out.println("exit code: " + result);
            } catch (IOException ex) {
                LOG.log(Level.SEVERE, null, ex);
            } catch (InterruptedException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }    
    
    private void sendInput(Process process, String input, String encoding)
            throws IOException {
    
        try (OutputStream stream = process.getOutputStream();
                Writer writer = new OutputStreamWriter(
                        stream, encoding == null ? "UTF-8" : encoding);
                PrintWriter out = new PrintWriter(writer)) {
            if (input != null) {
                Reader reader = new StringReader(input);
                BufferedReader in = new BufferedReader(reader);
                String line = in.readLine();
                while (line != null) {
                    out.println(line);
                    line = in.readLine();
                }
            }
        }
    }
    
        private static class OutputHandler extends Thread {
            private BufferedReader in;
    
            private OutputHandler(InputStream in, String encoding)
                    throws UnsupportedEncodingException {
                this.in = new BufferedReader(new InputStreamReader(
                        in, encoding == null ? "UTF-8" : encoding));
            }
    
            @Override
            public void run() {
                try {
                    String s = in.readLine();
                    while (s != null) {
                        System.out.println(s);
                        s = in.readLine();
                    }
                } catch (IOException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        in.close();
                    } catch (IOException ex) {
                        LOG.log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }
    

    【讨论】:

    • 能否请您简要介绍一下我是 java 新手,我从未研究过多线程。
    • 请注意,如果您使用的是 ProcessBuilder,则可以执行 redirectErrorStream(true) 并且只需要一个线程。
    • 添加方法 sendInput
    • 非常感谢 Maurice Perry 的大力帮助,我为此苦苦挣扎了很长时间,现在它成功了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    相关资源
    最近更新 更多