本文介绍了使用Runtime.getRuntime()。exec(command);时,用户输入命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是不可能的,但是我一直在使用:

I dont think this is possible, but I have been using:

Process p = Runtime.getRuntime().exec(command);

可以在命令行上运行命令,但是现在我遇到了这样一种情况:

to run commands on the command line, but now I have come accross a situation where the command I am running part way through will ask for some user input, for example a username.

这无法通过正在执行的命令的参数来解决,是否有任何输入我可以如何将用户名传递给同一命令行实例并继续?

This can not be resolved by a argument to the command that is being exec, is there any way I can pass the username to the same command line instance and continue?

--- EDIT ---

---EDIT---

我仍然无法解决这个问题。这些是命令行上的步骤:

I still cant get this to work. These are the steps on the command line:

C:\someProgram.exe
Login:
Passowrd:

所以我需要在运行时提示时输入登录名和密码。我得到的代码不起作用:

So I need to pass the login and password when it prompts at runtime. The code I've got that doesnt work:

try {
        String CMD = "\"C:\\someProgram\"";
        Scanner scan = new Scanner(System.in);
        ProcessBuilder builder = new ProcessBuilder(CMD);
        builder.redirectErrorStream(true);
        Process process = builder.start();

        InputStream is = process.getInputStream();
        BufferedReader reader = new BufferedReader (new InputStreamReader(is));
        OutputStream out = process.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
        String line;
        try {
            while (scan.hasNext()) {
                String input = scan.nextLine();
                if (input.toLowerCase().startsWith("login")) {
                    writer.write("myUsername");
                } else if(input.toLowerCase().startsWith("password")){
                    writer.write("myPassword");
                }
                writer.flush();

                line = reader.readLine();
                while (line != null) {
                    System.out.println ("Stdout: " + line);
                    line = reader.readLine();
                }
                if (line == null) {
                    break;
                }
            }
            process.waitFor();
        }
        finally {;
            writer.close();
            reader.close();
        }
    }
    catch (Exception err) {
        System.err.println("some message");
    }

我尝试过以下操作:
writer.write( myUsername\ \n);

Ive tried things like: writer.write("myUsername\n");

任何帮助,我都可以看到someProgram.exe在进程中被调用并正在运行,但是它只是挂起了。

Any help, i can see that someProgram.exe is called and running in the processes, but it just hangs.

推荐答案

只需写入p.getOutputStream()。这样会将用户名发送到流程的标准输入,该标准输入应执行您想要的操作。

Just write to p.getOutputStream(). That'll send the username to the process's standard input, which should do what you want.

out = p.getOutputStream();
out.write("fooUsername\n".getBytes());
out.flush();

这篇关于使用Runtime.getRuntime()。exec(command);时,用户输入命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:33