D:\Documents and Settings\Administrator>netstat -ano -p tcpActive Connections  Proto  Local Address          Foreign Address        State           PID
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       1868
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:1110           0.0.0.0:0              LISTENING       1784
  TCP    0.0.0.0:6060           0.0.0.0:0              LISTENING       4164
  TCP    0.0.0.0:19780          0.0.0.0:0              LISTENING       1784
  TCP    127.0.0.1:3100         127.0.0.1:1110         TIME_WAIT       0
  TCP    127.0.0.1:3103         127.0.0.1:1110         TIME_WAIT       0
  TCP    127.0.0.1:3109         127.0.0.1:1110         TIME_WAIT       0
  TCP    127.0.0.1:3115         127.0.0.1:1110         TIME_WAIT       0
  TCP    127.0.0.1:3118         127.0.0.1:1110         TIME_WAIT       0
  TCP    192.168.1.10:139       0.0.0.0:0              LISTENING       4
  TCP    192.168.1.10:1160      219.133.49.211:80      ESTABLISHED     2980
  TCP    192.168.1.10:1260      221.176.31.1:8080      ESTABLISHED     2256
  TCP    192.168.1.10:2963      211.100.26.88:80       LAST_ACK        1784
  TCP    192.168.1.10:3111      211.100.26.88:80       LAST_ACK        1784D:\Documents and Settings\Administrator>
通过cmd运行上面的命令,能得到一些端口的占用情况和其进程ID
我如何通过JAVA程序的Runtime.getRuntime().exec运行,得到上面的6060这个端口所在的进程ID呢?

解决方案 »

  1.   

      TCP    0.0.0.0:6060          0.0.0.0:0              LISTENING      4164 
      

  2.   

    import java.io.*; public class Test {
     public static void main(String [] args) {
     try {
     Runtime rt = Runtime.getRuntime();
     Process ps = rt.exec("vi test.txt");
     OutputStream os = ps.getOutputStream();
     InputStream is = ps.getInputStream();
     DataOutputStream dos = new DataOutputStream(os);
     dos.writeBytes("i");
     dos.writeBytes("test");
     dos.writeBytes("u001B");
     dos.writeBytes(":wq");
     dos.flush();
     ps.waitFor();
     dos.close();
     System.out.println(ps.exitValue());
     }
     catch (Exception ex)
     {
     System.out.println(ex);
     }
     }
     }dos内容文本分析,呵呵dos内容
      

  3.   


    InputStream is=Runtime.getRuntime().exec("netstat -ano").getInputStream();
    InputStreamReader bis=new InputStreamReader(is);
    BufferedReader br=new BufferedReader(bis);
    String s="";
    String port=":8288";
    String pid="";
    while((s=br.readLine())!=null)
    {
    int index=s.indexOf(port);
    if(index>-1 && index<30)
    {
    if(pid.length()>0)
    pid+=";";
    pid+=s.substring(s.lastIndexOf(" ")+1);
    }
    }
    System.out.println(pid);