【发布时间】:2010-07-16 08:32:32
【问题描述】:
我正在尝试将一段用 Java 编写的代码(见下文)从 Linux 移植到 Windows,并成功了。
String sh = "/bin/sh";
String cop = "-c";
String cmd = "netstat -a | grep 9000 | wc -l";
String[] exe = new String[] {sh, cop, cmd};
Process FindConns = Runtime.getRuntime().exec(exe);
这实际上构建了一个命令并将其传递给 shell 执行并收集结果。
现在在 Windows 中,等效的命令是
netstat -a | find /c "9000"
但是,我不确定以下几点:-
-
对于 Windows 端口,应将什么命令字符串传递给“Runtime.getRuntime().exec()”。我试过了
String cmd = "netstat -a | find /c 9000";
//and String cmd = "netstat -a | find /c \"9000\""; 进程 FindConns = Runtime.getRuntime().exec(cmd);
但它失败了。似乎,在调试时,Windows 搞砸了 | (管道)字符。由于以下工作正常。
String cmd = "netstat -a";
Process FindConns = Runtime.getRuntime().exec(cmd);
- 其次,(Java 编程新手)在 Java 中进行条件编译(如 #ifdef WIN32 等)的最佳方法是什么。
谢谢。
【问题讨论】:
-
不要在一个 SO Question 中问两个不相关的问题。你现在应该知道了!
-
第二部分是相关的。我需要进行移植,并将使用第二部分来实现第一部分。