Java8 Base64 和文件互轉

import com.mysql.cj.util.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;

public class AnswerApp {

    public static void main(String[] args) throws Exception {
        String srcPath = "/home/jaemon/src/aal.jpg";
        String descPath = "/home/jaemon/desc";

        File srcFile = new File(srcPath);

        // 讀取文件的字節數組
        byte[] bytes = FileUtils.readFileToByteArray(srcFile);
        // 將文件字節數組 轉 hexstring(16進制字符串)
        String hexString = StringUtils.toHexString(bytes, bytes.length);


        // 16進制 字符串 轉 輸入流
        InputStream inputStream = hexToInputStream(hexString);
        // 輸入流 轉 文件
        FileUtils.copyInputStreamToFile(inputStream, new File(descPath + File.separator + "hex.jpg"));


        // 文件 轉 Base64
        String base64String = Base64.getEncoder().encodeToString(bytes);

        // Base64 轉 文件
        byte[] data = Base64.getDecoder().decode(base64String);
        FileUtils.writeByteArrayToFile(new File(descPath + File.separator + "base64.jpg"), data);
//        Files.write(Paths.get(descPath), data, StandardOpenOption.CREATE);
    }



	// 16 進制字符串轉 輸入流
    private static InputStream hexToInputStream(String hexString) {
        byte[] bytes = hexStringToBytes(hexString);
        Assert.notNull(bytes, "bytes is null.");
        return new ByteArrayInputStream(bytes);
    }

	// 16 進制字符串轉 字節數組
    private static byte[] hexStringToBytes(String hexString) {
        if (org.springframework.util.StringUtils.isEmpty(hexString)) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}

Base64Utils 源碼

發佈了159 篇原創文章 · 獲贊 28 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章