简体   繁体   English

在新进程上启动cmd.exe,然后在其上启动用户扫描仪

[英]Start cmd.exe on new Process then user Scanner on it

Is there a way to open a cmd.exe via ProcessBuilder and then reference its streams such that one could call NewProcessOutputStream.println() and Scanner s = new Scanner(NewProcessInputStream) ? 有没有一种方法可以通过ProcessBuilder打开cmd.exe ,然后引用其流,以便可以调用NewProcessOutputStream.println()Scanner s = new Scanner(NewProcessInputStream)

I am aware that I can issue a command such as cmd /c dir and read the input stream, but I would like to open the cmd process, then access its streams such that I can print to it whenever. 我知道我可以发出诸如cmd /c dir类的命令并读取输入流,但是我想打开cmd进程,然后访问其流,以便可以在任何时候打印到它。

Is what I am thinking of possible? 我在想什么可能吗? Or should I be executing another program via the process? 还是应该通过该过程执行另一个程序?

Edit (Updated): Output not what expected 编辑(更新):输出不符合预期

import java.io.*;
import java.util.*;

public class Terminal {
    public static void main(String[] args) throws IOException {

        Process cmd = new ProcessBuilder("cmd").start();

        PrintWriter writer = new PrintWriter(cmd.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(cmd.getInputStream()));

        writer.println("Hello");
        writer.println("World!");
        writer.println("How are you?");
        writer.close();

        String line;

        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
}

Output: 输出:

C:\Users\Paul\Desktop\temp\CLI\src>java Terminal
Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\Paul\Desktop\temp\CLI\src>Hello

C:\Users\Paul\Desktop\temp\CLI\src>World!

C:\Users\Paul\Desktop\temp\CLI\src>How are you?

C:\Users\Paul\Desktop\temp\CLI\src>

C:\Users\Paul\Desktop\temp\CLI\src>

Yes, you can get the process input using Process.getOutputStream() and its output using Process.getInputStream() . 是的,你可以用获得的过程输入Process.getOutputStream()并使用其输出Process.getInputStream()

Here's an example: 这是一个例子:

public class ProcessTest {

    public static void main(String[] args) throws IOException {
        Process grep = new ProcessBuilder("grep", "foo").start();

        PrintWriter writer = new PrintWriter(grep.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(grep.getInputStream()));

        writer.println("this is the first line");
        writer.println("this is the foo line");
        writer.println("this is the last line");
        writer.println("nope, another foo");
        writer.close();

        // EDIT: fixed end of stream check
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
        reader.close();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM