보통 일반적으로 Java 함수내의 명령어를 사용하는 것을 권장합니다.
그 이유는 OS에 상관 없이 작동하기때문입니다.
아래의 경우는 부득이한 경우에 사용해야 합니다.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShellCommander {
public static void main(String[] args) throws Exception {
String command = "ls -al";
// 이 부분에 실행할 리눅스 Shell 명령어를 입력하면 된다. (여기선 ls -al 명령어 입력)
shellCmd(command);
}
public static void shellCmd(String command) throws Exception {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
|