Java Runtime.getRunTime().exec(CMD)不支持管道
我正在尝试编写一个程序,该程序将显示并能够使用JFrame窗口更新您的IP地址设置。我希望纯粹在windows上运行它,因此我尝试使用netsh windows命令来检索/设置详细信息 windows命令:Java Runtime.getRunTime().exec(CMD)不支持管道,java,windows,command,cmd,pipe,Java,Windows,Command,Cmd,Pipe,我正在尝试编写一个程序,该程序将显示并能够使用JFrame窗口更新您的IP地址设置。我希望纯粹在windows上运行它,因此我尝试使用netsh windows命令来检索/设置详细信息 windows命令: netsh接口ip show config name=“局域网连接”|查找“ip” 返回我希望它返回的内容,但是我编写的代码无法通过管道工作,它只能在我编写到“本地连接”部分时工作 是否有任何方法可以使用管道功能只返回IP地址?我读到,您可以将该行作为字符串数组传递,即string[]cmd
netsh接口ip show config name=“局域网连接”|查找“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();
}
}
我想你们可以帮忙。幸运的是,有一种方法可以运行包含管道的命令。该命令的前缀必须为
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();
}
注释
- Windows控制台使用
编码。看IBM850
- 有关
的信息,请参阅使用分隔符(\\A”)
sh-c“ls | wc”
或cmd/c“dir”| find“T\”
。我该怎么做呢?我只是java的新手,还在学习诀窍。别担心,我刚刚解决了这个问题!我很感激,谢谢@KaneCharles-您应该发布自己的答案,然后选择它!:)解决办法是什么?