Java write netstat in cmd

My goal is to print all internet connections on my computer. When I type netstat on cmd, I get a list of internet connections. I wanted to do the same in java, automatically.

My code is:

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 

But with this code, do I get C: \ eclipse \ workspace \ Tracker> Mais? instead of the netlist. Obviously, I am working with eclipse on Windows 7. What am I doing wrong? I looked in similar topics, but I did not find what was wrong. Thanks for answers.

EDIT:

 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); } } 
+4
source share
3 answers

Try the following: I was able to create a file in my default temporary directory with all connections

 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); } 
0
source

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(); } 
0
source
 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; } 
-1
source

All Articles