如何运行Linux命令&x201C;netstat”;来自Java程序?
我有一个用Java编写的客户机-服务器项目,其中它们通过套接字进行连接。我不知道如何从Java代码的服务器端运行“netstat” 不幸的是,java中没有直接可用的netstat等价物 您可以使用流程API生成新流程并检查输出 我将使用以下q/a中的一个示例: 我已将其更改为调用如何运行Linux命令&x201C;netstat”;来自Java程序?,java,linux,server-side,serversocket,Java,Linux,Server Side,Serversocket,我有一个用Java编写的客户机-服务器项目,其中它们通过套接字进行连接。我不知道如何从Java代码的服务器端运行“netstat” 不幸的是,java中没有直接可用的netstat等价物 您可以使用流程API生成新流程并检查输出 我将使用以下q/a中的一个示例: 我已将其更改为调用netstat。在生成进程之后,您还必须读取输出并对其进行解析 Runtime rt = Runtime.getRuntime(); String[] commands = {"netstat", ""}; Proce
netstat
。在生成进程之后,您还必须读取输出并对其进行解析
Runtime rt = Runtime.getRuntime();
String[] commands = {"netstat", ""};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
资料来源:看一下有什么目的?你不应该需要这个。一般情况下这不起作用。您要么需要合并流,要么在单独的线程中并发读取它们。@user207421您说得对!,只要进程运行第一个while循环,它就会阻塞另一个while循环。我会更新这个。