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? 而不是连接列表。显然我正在使用 Eclipse,在 Windows 7 中。我做错了什么?我看过类似的主题,但我找不到什么问题。谢谢你的回答。

编辑:

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 回答
-2
final String cmd = "netstat -ano";

    try {

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

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

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


    } catch (Exception e) {
        e.printStackTrace(System.err);
    } finally{
        in  = null;
        isr = null;
        br = null;
    }
于 2018-04-10T21:07:29.127 回答