2013-10-14 7 views
1

Java 내에서 Mac OSX에서 시스템 명령을 실행할 수 있기를 원합니다. 내 코드는 다음과 같습니다Mac에서 Java로 시스템 명령 실행

public void checkDisks() throws IOException, InterruptedException { 
    Process p = Runtime.getRuntime().exec("df -h"); 
    int exitValue = p.waitFor(); 
    System.out.println("Process exitValue:" + exitValue); 


    BufferedReader reader = new BufferedReader(new InputStreamReader(
               p.getInputStream())); 
    String line = reader.readLine(); 
    while (line != null) { 
     line = reader.readLine(); 
    } 
    System.out.println(line); 
} 

이 항상 null을 반환과 0의 exitValue이 전에 자바 그래서 어떤 생각이나 제안이 크게 감사 수행하지 마십시오.

+0

0 "DF -h"명령의 정상적인 실행을 나타냅니다 노력하지만 왜 페이지에서의 InputStream을 읽으려는? 대신 파일에서 읽을 수 있습니다. –

답변

2

귀하의 코드는 거의 OK입니다, 당신은 단지 println 메소드

public void checkDisks() throws IOException, InterruptedException { 
    Process p = Runtime.getRuntime().exec("df -h"); 
    int exitValue = p.waitFor(); 
    System.out.println("Process exitValue:" + exitValue); 


    BufferedReader reader = new BufferedReader(new InputStreamReader(
               p.getInputStream())); 
    String line = reader.readLine(); 
    while (line != null) { 
     line = reader.readLine(); 
     System.out.println(line); 
    } 
} 

에게 잘못 나는 당신이 달성하기 위해 노력하고 무엇을 생각합니다.

+0

또는 아마 "line + = reader.readLine()"! –

+0

테스트 목적으로 사용됩니다. 프로덕션 환경에서 사용할 때는 StringBuilder를 사용하는 것이 좋습니다. – BaRoN

1

public void checkDisks() throws IOException, InterruptedException { 
    Process p = Runtime.getRuntime().exec(new String[]{"df","-h"}); 
    int exitValue = p.waitFor(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(
               p.getInputStream())); 
    String line; 
    while ((line=reader.readLine()) != null) { 
      System.out.println(line); 
    } 
    System.out.println("Process exitValue:" + exitValue); 
} 
관련 문제