SeouliteLab

[Java/자바] Java에서 윈도우 CMD 명령어 실행 및 결과 출력하기 본문

프로그래밍

[Java/자바] Java에서 윈도우 CMD 명령어 실행 및 결과 출력하기

Seoulite Lab 2024. 3. 9. 01:09

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를 설정하여 외부 프로세스 실행을 제어할 수 있습니다. 이를 통해 악의적인 명령어 실행을 방지하고 시스템 보안을 강화할 수 있습니다.