在Java中获取“cmd.exe”的输出流

时间:2013-09-15 08:27:14

标签: java

我想在Windows中为命令行创建类似遥控器的东西。

为此,我使用的是扫描仪,但是......

问题是,当我从流中读取nextLine()的整行时,提示将会丢失(因为打印了,但不是一行) - 当我用next()读取下一个单词时,缺少换行符,你将失去概述。但是,有些信息甚至丢失了。

package com;

import java.io.IOException;
import java.util.Scanner;

public class StdinCmd extends Thread {
    public void run() {
        try {
            execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void execute() throws IOException {
        Scanner reader = new Scanner(MainClient.getProcess().getInputStream()); // <- getting the stream
        StdoutSocket stdoutSocket = new StdoutSocket();
        while (true) {
            while (reader.hasNext()) {
                stdoutSocket.executeNext(reader.next()); // <- send it to the socket (the controller). This is what will be displayed at the end.
            }
        }
    }
}

我附上了它应该是什么样子的截图,以及它最终的结果:

http://www.mediafire.com/?jma31ezg8ansfal

我希望你能帮助我,我给了你足够的信息!

2 个答案:

答案 0 :(得分:1)

请勿使用ScannerBufferedReader,而是直接从InputStream ...

阅读
InputStream is = null;
try {
    is = MainClient.getProcess().getInputStream();
    int in = -1;
    while ((in = is.read()) != -1) {
        System.out.print(((char)in));
    }
} catch (IOException exp) {
    exp.printStackTrace();
} finally {
    try {
        is.close();
    } catch (Exception exp) {
    }
}

答案 1 :(得分:1)

就我个人而言,我真的不喜欢扫描仪。如果你想从用户那里读取输入行并通过套接字发送它。那么谁不能只使用带有System.in的BufferedReader? 读一行并通过套接字发送。

BufferedReader br = new BUfferedReader(new InputStreamReader(System.in));
String line = null;
while((line = br.readLine()) != null){
    OutSocket.send(line); // or how you send it..
}

〜Foorack

相关问题