자바에서는 Runtime 클래스를 통해 운영체제와 상호작용을 할 수 있다.
리눅스 또한 Runtime 클래스를 통해 조작할 수 있다.
다음과 같이 getRuntime() 메서드로 현재 실행중인 운영체제를 Runtime 객체로 생성한 후
exec() 메소드를 사용해 명령어를 수행하도록 할 수 있다.
Runtime rt = Runtime.getRuntime();
rt.exec("명령어1");
rt.exec("명령어2");
여기서 exec() 메서드는 Process라는 클래스의 인스턴스를 반환한다. Process 클래스의 인스턴스를 사용하여 명령어 수행으로 화면에 출력될 내용을 InputStream으로 받을 수 있다. 이 내용을 리눅스 터미널에 출력하기 위해서는 System.out의 메소드들을 사용하면 된다.
import java.io.*;
public class test5 {
public static void main(String[] args) {
try{
Process ps = Runtime.getRuntime().exec("ps");
BufferedReader reader = new BufferedReader(new InputStreamReader(ps.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = ps.waitFor();
System.out.println("Command executed, exit code : " + exitCode);
} catch (IOException | InterruptedException e){
e.printStackTrace();
}
}
}
'Linux' 카테고리의 다른 글
[Linux] sftp (0) | 2023.08.19 |
---|---|
[Linux] g++를 사용한 C++ 컴파일 (0) | 2023.08.17 |
리눅스 기본 명령어 (0) | 2023.01.01 |
우분투 20.04 SVN 서버 설정 (0) | 2022.12.29 |
우분투 20.04 윈도우 공유 폴더 접근하기 (0) | 2022.12.28 |