简体   繁体   English

是否可以将Windows控制台输出定向到GUI?

[英]Is is possible to direct windows console output to a GUI?

I'm working on a project and I would like to execute programs in the windows console or a linux terminal. 我正在研究一个项目,我想在Windows控制台或Linux终端中执行程序。

Instead of launching a new console and working the program in it I want to do something like the following: 与其启动新控制台并在其中运行程序,不如执行以下操作:

rt.exec("cmd.exe /c start cmd.exe /k ruby rubycode.rb");

From this point on I want the user to be able to work with the program from the GUI/my program. 从现在开始,我希望用户能够使用GUI /我的程序中的程序。 The idea in my min is starting cmd in silent mode where it is not visible and latching on to it. 我的想法是在不可见的静音模式下启动cmd并锁定它。 Then redirecting the console output to the GUI and letting the user input data to the console through the GUI. 然后将控制台输出重定向到GUI,并让用户通过GUI将数据输入到控制台。

A similar concept is what most IDEs like jgrasp do. 类似的概念是大多数IDE(如jgrasp)所做的。 When you run a program you interface with it though their own command prompt. 当您运行程序时,将通过其自己的命令提示符与之交互。

How is this done? 怎么做? Iv'e tried grabbing the IOStreams from the process and trying to atleast print what the console outputs but no luck. 我尝试从进程中获取IOStream,并尝试至少打印控制台输出的内容,但没有运气。

Here is an example: 这是一个例子:

public class ProcessTest {
private Process p;
private BufferedReader reader;
private BufferedWriter writer;

public void start() throws IOException {
    ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "dir");
    pb.directory(new File("./"));
    this.p = pb.start();
    this.reader = new BufferedReader(new InputStreamReader(this.p.getInputStream()));
    this.writer = new BufferedWriter(new OutputStreamWriter(this.p.getOutputStream()));
    new Read(this.reader).start();
}

public boolean writeToConsole(String s) throws IOException {
    if (p == null)
        return false;
    this.writer.write(s + "\n");
    this.writer.flush();
    return true;
}

public class Read extends Thread {
    private BufferedReader reader;

    public Read(BufferedReader reader) {
        this.reader = reader;
    }

    public void run() {
        try {
            String line;
            while ((line = this.reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args) {
    try {
        new ProcessTest().start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

With the writeToConsole method you can write any string to the programm that you executed. 使用writeToConsole方法,可以将任何字符串写入执行的程序。

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

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