java在netstat中写cmd [英] java write netstat in cmd
问题描述
我的目标是在我的计算机上打印所有互联网连接。当我键入netstat在cmd我获得互联网连接列表。我想在java中自动执行相同的操作。
My goal is to print all the internet connections on my computer. When i type netstat on cmd i get the internet connections list. I wanted to do the same in java, automatically.
我的代码:
Runtime runtime = Runtime.getRuntime();
process = runtime.exec(pathToCmd);
byte[] command1array = command1.getBytes();//writing netstat in an array of bytes
OutputStream out = process.getOutputStream();
out.write(command1array);
out.flush();
out.close();
readCmd(); //read and print cmd
但是使用这个代码我得到C:\eclipse\workspace\\ \\ Tracker> Mais?而不是连接列表。显然我正在使用eclipse,在windows 7.我做错了什么?我看过类似的话题,但我不能找到什么错。感谢您的答案。
But with this code i get C:\eclipse\workspace\Tracker>Mais? instead of the list of connections. Obviously i'm working with eclipse, in windows 7. What am I doing wrong? I've looked in similar topics but i cound't find whats wrong. Thank you for the answers.
编辑:
public static void readCmd() throws IOException {
is = process.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
推荐答案
也可以使用 <$ c $的实例c> java.util.Scanner 读取命令的输出。
You can also use an instance of java.util.Scanner
to read the output of the command.
public static void main(String[] args) throws Exception {
String[] cmdarray = { "netstat", "-o" };
Process process = Runtime.getRuntime().exec(cmdarray);
Scanner sc = new Scanner(process.getInputStream(), "IBM850");
sc.useDelimiter("\\A");
System.out.println(sc.next());
sc.close();
}
这篇关于java在netstat中写cmd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!