728x90
반응형

파일을 Base64로 인코딩, 디코딩하는 방법

 

파일을 base64로 인코딩

예제

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

public class FileToBase64Encoder {

    public static String encodeFileToBase64(File file) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] fileBytes = new byte[(int) file.length()];
            fileInputStream.read(fileBytes);
            return Base64.getEncoder().encodeToString(fileBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        File file = new File("path/to/your/file.txt");
        String base64String = encodeFileToBase64(file);
        System.out.println(base64String);
    }
}

 


base64로 인코딩된 파일을 디코딩

예제

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class Base64ToFileDecoder {

    public static void decodeBase64ToFile(String base64String, String outputFilePath) {
        try (FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath)) {
            byte[] fileBytes = Base64.getDecoder().decode(base64String);
            fileOutputStream.write(fileBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String base64String = "your_base64_encoded_string_here";
        String outputFilePath = "path/to/your/output/file.txt";
        decodeBase64ToFile(base64String, outputFilePath);
    }
}
반응형
복사했습니다!