我正在尝试编写一个程序,该程序将显示并能够使用 JFrame 窗口更新您的 IP 地址设置。我正在考虑纯粹在 Windows 上运行它,因此我尝试能够使用 netsh windows 命令来检索/设置详细信息。
Windows命令:netsh interface ip show config name="Local Area Connection" | Find "IP"
返回的正是我想要的,但是我编写的代码将无法通过管道工作,只有当我编写到“本地连接”部分时它才会工作。
有什么方法可以使用管道功能来专门返回 IP 地址吗?我读到您可以将该行作为字符串数组传递,即 String[] cmd = netsh........
package ipchanger;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class test {
private String CMD;
public void executecommand(String CMD) {
this.CMD = CMD;
try {
// Run whatever string we pass in as the command
Process process = Runtime.getRuntime().exec(CMD);
// Get input streams
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// Read command standard output
String s;
System.out.println("Standard output: ");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read command errors
System.out.println("Standard error: ");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public test() {
String FINDIP = "netsh interface ip show config name=\"Local Area Connection\" | Find \"IP\"";
//System.out.println(FINDIP);
executecommand(FINDIP);
}
public static void main(String[] args) {
new test();
}
}
我想你们也许能帮忙。
幸运的是,有一种方法可以运行包含以下内容的命令:pipes。该命令必须带有前缀cmd /C
. e.g.:
public static void main(String[] args) throws Exception {
String command = "cmd /C netstat -ano | find \"3306\"";
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
if (process.exitValue() == 0) {
Scanner sc = new Scanner(process.getInputStream(), "IBM850");
sc.useDelimiter("\\A");
if (sc.hasNext()) {
System.out.print(sc.next());
}
sc.close();
} else {
Scanner sc = new Scanner(process.getErrorStream(), "IBM850");
sc.useDelimiter("\\A");
if (sc.hasNext()) {
System.err.print(sc.next());
}
sc.close();
}
process.destroy();
}
Notes
- Windows使用的控制台
IBM850
编码。看java控制台输出的默认字符编码.
- See 愚蠢的扫描仪技巧... for
useDelimiter("\\A")
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)