有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在cmd中编写netstat

我的目标是在我的电脑上打印所有的互联网连接。当我在cmd上键入netstat时,我会得到internet连接列表。我想在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>;梅斯?而不是连接列表。显然,我是在Windows7中使用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);
    }
}

共 (3) 个答案

  1. # 1 楼答案

    试试这个:我可以在默认的临时目录中创建一个包含所有连接的文件

    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);
            }
    
  2. # 2 楼答案

    您还可以使用^{}的实例来读取命令的输出

    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();
    }
    
  3. # 3 楼答案

    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;
        }