Jansi는 자바에서 ANSI 이스케이프 코드를 사용하여 터미널의 색상, 커서 이동, 화면 지우기 등의 작업을 수행할 수 있게 해주는 라이브러리입니다. 이번 블로그 포스트에서는 Jansi를 사용하여 자바에서 터미널에서 파일을 이동하는 방법을 알아보겠습니다.
Jansi 설치하기
먼저, Maven을 사용한다면 pom.xml
파일에 다음 종속성을 추가해주세요:
<dependencies>
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>1.18</version>
</dependency>
</dependencies>
Gradle을 사용한다면 build.gradle
파일에 다음 종속성을 추가해주세요:
dependencies {
implementation 'org.fusesource.jansi:jansi:1.18'
}
이제 Jansi를 사용할 준비가 되었습니다.
터미널에서 파일 이동하기
Jansi를 사용하여 터미널에서 파일을 이동하기 위해서는 먼저 MoveFileCommand
클래스를 만들어야 합니다. 이 클래스는 java.lang.ProcessBuilder
를 사용하여 터미널 명령을 실행하고 결과를 반환하는 역할을 합니다.
import org.fusesource.jansi.AnsiConsole;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class MoveFileCommand {
public static void main(String[] args) throws IOException {
AnsiConsole.systemInstall();
String sourceFilePath = "/path/to/source/file.txt";
String destinationFilePath = "/path/to/destination/file.txt";
moveFile(sourceFilePath, destinationFilePath);
AnsiConsole.systemUninstall();
}
public static void moveFile(String sourcePath, String destinationPath) throws IOException {
Path source = Path.of(sourcePath);
Path destination = Path.of(destinationPath);
// Copy the file to the destination
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
// Delete the source file
Files.delete(source);
// Print the success message
System.out.println("File moved successfully!");
}
}
MoveFileCommand
클래스의 main
메서드에서는 sourceFilePath
와 destinationFilePath
를 설정하고, moveFile
메서드를 호출하여 파일을 이동합니다. moveFile
메서드는 java.nio.file.Files
클래스의 copy
메서드를 사용하여 파일을 복사하고, delete
메서드를 사용하여 원본 파일을 삭제합니다.
터미널에서 실행한 후, sourceFilePath
에 지정한 파일은 destinationFilePath
로 이동됩니다.
결론
Jansi를 사용하면 자바에서 터미널에서 파일을 이동할 수 있습니다. 터미널 명령을 실행하고 결과를 처리하는 ProcessBuilder
를 사용하면 파일 이동 외에도 다양한 터미널 작업을 자바에서 수행할 수 있습니다.