4

私の目標は、コンピューター上のすべてのインターネット接続を印刷することです。cmd で netstat と入力すると、インターネット接続リストが表示されます。私は自動的にJavaで同じことをしたいと思っていました。

私のコード:

Runtime runtime = Runtime.getRuntime();

process = runtime.exec(pathToCmd);

byte[] command1array = command1.getBytes();//writing netstat in an array of bytes
OutputStream out = process.getOutputStream();
out.write(command1array);
out.flush();
out.close();

readCmd();  //read and print cmd

しかし、このコードでは C:\eclipse\workspace\Tracker>Mais? 接続のリストの代わりに。明らかに、Windows 7でEclipseを使用しています。何が間違っていますか? 同様のトピックを調べましたが、何が問題なのかわかりませんでした。回答ありがとうございます。

編集:

public static void readCmd() throws IOException {

    is = process.getInputStream();
    isr = new InputStreamReader(is);
    br = new BufferedReader(isr);
    String line;

    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}
4

3 に答える 3

0

これを試してください:すべての接続を使用して、デフォルトの一時ディレクトリにファイルを作成できました

final String cmd = "netstat -ano";

        try {

            Process process = Runtime.getRuntime().exec(cmd);

            InputStream in = process.getInputStream();

            File tmp = File.createTempFile("allConnections","txt");

            byte[] buf = new byte[256];

            OutputStream outputConnectionsToFile = new FileOutputStream(tmp);

            int numbytes = 0;

            while ((numbytes = in.read(buf, 0, 256)) != -1) {

                outputConnectionsToFile.write(buf, 0, numbytes);

            }

            System.out.println("File is present at "+tmp.getAbsolutePath());


        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
于 2013-04-02T20:38:39.557 に答える
-1

のインスタンスを使用してjava.util.Scanner、コマンドの出力を読み取ることもできます。

public static void main(String[] args) throws Exception {
    String[] cmdarray = { "netstat", "-o" };
    Process process = Runtime.getRuntime().exec(cmdarray);
    Scanner sc = new Scanner(process.getInputStream(), "IBM850");
    sc.useDelimiter("\\A");
    System.out.println(sc.next());
    sc.close();
}
于 2014-04-04T16:47:23.513 に答える