我的目标是在我的计算机上打印所有互联网连接。当我在cmd上键入netstat时,我会获得互联网连接列表。我想在java中自动执行相同的操作。
我的代码:
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?而不是连接列表。显然我正在使用Windows 7中的eclipse。我做错了什么?我看过类似的话题,但我找不到什么错。谢谢你的答案。
编辑:
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);
}
}
答案 0 :(得分:0)
试试这个:我能够在我的默认临时目录中创建一个包含所有连接的文件
final String cmd = "netstat -ano";
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStream in = process.getInputStream();
File tmp = File.createTempFile("allConnections","txt");
byte[] buf = new byte[256];
OutputStream outputConnectionsToFile = new FileOutputStream(tmp);
int numbytes = 0;
while ((numbytes = in.read(buf, 0, 256)) != -1) {
outputConnectionsToFile.write(buf, 0, numbytes);
}
System.out.println("File is present at "+tmp.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace(System.err);
}
答案 1 :(得分:0)
您还可以使用java.util.Scanner
的实例来读取命令的输出。
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();
}
答案 2 :(得分:-1)
final String cmd = "netstat -ano";
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStream in = process.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace(System.err);
} finally{
in = null;
isr = null;
br = null;
}