2013-03-31 2 views
4

내 목표는 내 컴퓨터에 모든 인터넷 연결을 인쇄하는 것입니다. 내가 cmd를 입력하면 netstat 인터넷 연결 목록을 얻을. 나는 자바에서 자동으로 동일하게하고 싶었다.java write netstat in cmd

내 코드 :

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 : \ 이클립스 \ 작업 공간 \ 추적기> 더보기? 연결 목록 대신. 분명히 내가 일식, 윈도우 7에서 일하고 있어요. 내가 뭘 잘못하고있어? 나는 비슷한 주제를 쳐다 보았지만 잘못된 점을 발견하지 못했습니다. 답변 해 주셔서 감사합니다.

편집 :

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); 
    } 
} 
+1

'Runtime' 대신'ProcessBuilder'를 사용해야하고'readCmd()'를 보여 주어야합니다. 아마 그 오류가 거기에있다. – Zhedar

+0

괜찮 았습니다. 'readCmd'가 괜찮은 것 같습니다. 아마도'OutputStream'을 래핑하는'PrintWriter'를 사용해보십시오. 나는 또한이 문제를 언젠가 전에 만났다. 아직도 모릅니다. 왜 그런 일이 일어 났습니까? – Zhedar

+0

'command1'은 어떻게 정의되어 있습니까? – neutrino

답변

0

이 시도 : 나는 당신은 또한을 읽을 수 java.util.Scanner의 인스턴스를 사용할 수 있습니다

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

모든 연결 내 기본 임시 디렉토리에 파일을 생성 할 수 있었다 명령의 출력.

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