将数据从 PrintStream 写入 "Console as Process" 而不是 Java 中的 "console as System.out" 时出现问题

Problem writing data from PrintStream to "Console as Process" and not "console as System.out" in Java

在 Java 8,windows 10,我有一个文本应用程序,我想打开一个控制台并在那里写点东西,

第一次尝试是:

    String [] cmd = {"cmd.exe", "/c", "start"};
    ProcessBuilder f = new ProcessBuilder(cmd);
    f.redirectErrorStream(true);
    Process p = f.start();
    PrintStream printStream=new PrintStream(p.getOutputStream());
    //
    System.setOut(printStream);
    System.out.println("this write in CMD"); //did not work 

第二次尝试是:

    printStream.println("this write in CMD");//did not work 

任何人都可以帮忙吗?

改为启动 conhost.exe,并写入保留进程的标准输入,或者如果您将输出流重定向到进程,则使用 System.out 写入将出现在新控制台 window:

String [] cmd = {"conhost.exe"};
ProcessBuilder f = new ProcessBuilder(cmd);
f.redirectErrorStream(true);
Process p = f.start();
PrintStream printStream=new PrintStream(p.getOutputStream());
System.setOut(printStream);
System.out.println("dir");