[java] Jansi를 활용하여 자바에서 터미널에서 디렉토리 이름 변경하기

이번 포스트에서는 자바 프로그램에서 터미널에서 디렉토리의 이름을 변경하는 방법에 대해 알아보겠습니다. 우리는 Jansi 라이브러리를 사용하여 이 작업을 수행할 것입니다.

Jansi 라이브러리란?

Jansi는 자바 어플리케이션에서 ANSI 이스케이프 시퀀스를 사용하여 터미널 출력을 제어하기 위해 사용되는 라이브러리입니다. 이 라이브러리는 ANSI 이스케이프 시퀀스를 처리하고, 터미널 색상 및 스타일을 변경하는 등의 작업을 수행할 수 있도록 도와줍니다.

디렉토리 이름 변경하기

아래의 코드는 Jansi를 활용하여 자바 프로그램에서 터미널에서 디렉토리의 이름을 변경하는 예제입니다.

import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;

public class DirectoryRenamer {

    public static void main(String[] args) {
        // Jansi 초기화
        AnsiConsole.systemInstall();

        // 변경할 디렉토리 경로 설정
        String directoryPath = "/path/to/directory";

        // 변경할 디렉토리 이름 설정
        String newDirectoryName = "new_directory_name";

        // 디렉토리 이름 변경하기
        AnsiConsole.out().println(Ansi.ansi().fg(Ansi.Color.GREEN).a("Renaming directory...").reset());
        String command = "mv " + directoryPath + " " + newDirectoryName;
        try {
            Process process = Runtime.getRuntime().exec(command);
            process.waitFor();
            AnsiConsole.out().println(Ansi.ansi().fg(Ansi.Color.GREEN).a("Directory renamed successfully!").reset());
        } catch (Exception e) {
            AnsiConsole.err().println(Ansi.ansi().fg(Ansi.Color.RED).a("Failed to rename directory: " + e.getMessage()).reset());
        }

        // Jansi 정리
        AnsiConsole.systemUninstall();
    }
}

위의 코드에서는 먼저 Jansi를 초기화한 다음, 변경할 디렉토리 경로와 새로운 디렉토리 이름을 설정합니다. 그런 다음, Runtime.getRuntime().exec() 메소드를 사용하여 터미널에서 mv 명령어를 실행하여 디렉토리 이름을 변경합니다.

명령어 실행 결과를 적절한 ANSI 이스케이프 시퀀스를 사용하여 터미널에 출력합니다. 성공적으로 디렉토리 이름을 변경하면 “Directory renamed successfully!” 메시지가 출력됩니다.

위의 코드를 실행하기 전에 Jansi 라이브러리를 프로젝트에 추가해야 합니다.

결론

Jansi를 사용하여 자바에서 터미널에서 디렉토리 이름을 변경하는 방법을 알아보았습니다. 이를 통해 자바 프로그램에서 터미널 작업을 제어하고, 터미널 출력을 스타일링 할 수 있습니다. Jansi를 사용하면 자바와 터미널 간의 통합을 간편하게 수행할 수 있습니다.

참고 자료