Total Pageviews

2018/11/15

[Java 8] How to do Base64 Encoding and Decoding?

Example

package com.example.demo.util;

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

public class FileUtils {

    public static String encodeToBase64String(File file) throws IOException {
        String base64Image = "";
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            byte imageData[] = new byte[(int) file.length()];
            imageInFile.read(imageData);
            base64Image = Base64.getEncoder().encodeToString(imageData);
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Image not found");
        } catch (IOException e) {
            throw new IOException("Exception when reading image", e);
        }
        return base64Image;
    }

    public static void decodeToImage(String base64Image, String pathFile) throws IOException {
        try (FileOutputStream imageOutFile = new FileOutputStream(pathFile)) {
            byte[] imageByteArray = Base64.getDecoder().decode(base64Image);
            imageOutFile.write(imageByteArray);
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Image not found");
        } catch (IOException e) {
            throw new IOException("Exception when reading image", e);
        }
    }

}


No comments: