Notice
Recent Posts
Recent Comments
Link
SeouliteLab
[Java/자바] Java에서 윈도우 CMD 명령어 실행 및 결과 출력하기 본문
Java 프로그램에서 윈도우 CMD(Command Prompt) 명령어를 실행하고 결과를 출력하는 것은 매우 유용한 기능입니다. 이번 글에서는 Java에서 CMD 명령어를 실행하는 여러 가지 방법과 예제를 살펴보겠습니다.
1. Runtime 클래스를 이용한 방법
가장 간단한 방법은 Runtime 클래스를 사용하여 CMD 명령어를 실행하는 것입니다. 이 방법은 간단하지만 프로세스를 생성하고 명령어를 실행하는 과정이 외부 프로세스로 분리되어 안정성과 보안에 취약할 수 있습니다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CMDExample {
public static void main(String[] args) {
try {
String command = "dir"; // 실행할 명령어
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // 명령어 실행 결과 출력
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. ProcessBuilder 클래스를 이용한 방법
ProcessBuilder 클래스를 사용하여 더 세밀하게 외부 프로세스를 제어할 수 있습니다. 이 방법은 프로세스 생성, 환경 설정, 명령어 실행 등을 더욱 유연하게 처리할 수 있습니다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CMDExample {
public static void main(String[] args) {
try {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "dir"); // 실행할 명령어
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // 명령어 실행 결과 출력
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. SecurityManager 설정
SecurityManager를 설정하여 외부 프로세스 실행을 제어할 수 있습니다. 이를 통해 악의적인 명령어 실행을 방지하고 시스템 보안을 강화할 수 있습니다.
'프로그래밍' 카테고리의 다른 글
[Java/자바] Selenium 드라이버 자동 설치 방법 (0) | 2024.03.09 |
---|---|
[Java/자바] 키보드, 마우스 이벤트 후킹하기 (0) | 2024.03.09 |
[Java/자바] HttpClient에 Timeout 설정하기 (0) | 2024.03.09 |
[Java/자바] NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper 에러 해결 방법 (0) | 2024.03.09 |
[Java/자바] AbstractMethodError의 원인과 해결 방법 (0) | 2024.03.09 |