繁体   English   中英

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

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

有没有一种方法可以通过ProcessBuilder打开cmd.exe ,然后引用其流,以便可以调用NewProcessOutputStream.println()Scanner s = new Scanner(NewProcessInputStream)

我知道我可以发出诸如cmd /c dir类的命令并读取输入流,但是我想打开cmd进程,然后访问其流,以便可以在任何时候打印到它。

我在想什么可能吗? 还是应该通过该过程执行另一个程序?

编辑(更新):输出不符合预期

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();
    }
}

输出:

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>

是的,你可以用获得的过程输入Process.getOutputStream()并使用其输出Process.getInputStream()

这是一个例子:

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