[java] 자바에서 RAR 파일을 압축 및 해제하는 방법

이 문서에서는 자바에서 RAR 파일을 압축하고 해제하는 방법을 설명합니다.

RAR 파일 압축하기

먼저 RAR 파일을 압축하기 전에 rar 명령어를 사용하여 필요한 도구를 설치해야 합니다. 아래의 링크를 통해 rar 도구를 다운로드하고 설치할 수 있습니다.

다음은 자바 코드를 통해 RAR 파일을 압축하는 예제입니다.

import java.io.*;
import java.util.zip.*;

public class RARCompressor {

    public static void compressFileToRAR(File fileToCompress, File compressedRAR) throws IOException {
        FileInputStream fis = new FileInputStream(fileToCompress);
        FileOutputStream fos = new FileOutputStream(compressedRAR);
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        ZipEntry zipEntry = new ZipEntry(fileToCompress.getName());
        zipOut.putNextEntry(zipEntry);

        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zipOut.write(bytes, 0, length);
        }

        zipOut.close();
        fos.close();
        fis.close();
    }

    public static void main(String[] args) {
        File fileToCompress = new File("/path/to/file/to/compress.txt");
        File compressedRAR = new File("/path/to/compressed/file.rar");

        try {
            compressFileToRAR(fileToCompress, compressedRAR);
            System.out.println("File compressed successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제 코드를 사용하면, compressFileToRAR 메소드를 통해 원하는 파일을 RAR 형식으로 압축할 수 있습니다.

RAR 파일 해제하기

RAR 파일을 해제하기 위해서는 RAR 파일을 압축할 때 사용한 rar 도구가 필요합니다. 다만, 자바에서 직접 RAR 파일을 해제하는 기능을 제공하지는 않습니다. 따라서, 명령어를 통해 RAR 파일을 해제해야 합니다. 아래의 코드는 자바에서 명령어를 실행하여 RAR 파일을 해제하는 방법을 보여줍니다.

import java.io.*;

public class RARExtractor {

    public static void extractRAR(File rarFile, File destinationDir) throws IOException {
        String command = "rar x " + rarFile.getAbsolutePath() + " " + destinationDir.getAbsolutePath();
        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);
        }

        process.destroy();
    }

    public static void main(String[] args) {
        File rarFile = new File("/path/to/compressed/file.rar");
        File destinationDir = new File("/path/to/extract/to/");

        try {
            extractRAR(rarFile, destinationDir);
            System.out.println("File extracted successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제 코드를 사용하면, extractRAR 메소드를 통해 RAR 파일을 원하는 디렉터리로 해제할 수 있습니다.


이 문서에서는 자바에서 RAR 파일을 압축 및 해제하기 위한 방법을 소개했습니다. 자세한 내용은 아래의 링크를 참조하시기 바랍니다.