天天看點

kafka 檔案轉字元串,字元串轉檔案

1.碰到一個需求就是需要把圖檔通過kafka發送出去.下面就可以轉換。

package com.pingan.company.controller;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class Test2 {


    /**
     * 字元串轉圖檔
     *
     * @param imgStr   --->圖檔字元串
     * @param filename --->圖檔名
     * @return
     */
    public static boolean generateImage(String imgStr, String filename) {

        if (imgStr == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            // 處理資料
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream("C:/tempfile/" + filename);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 圖檔轉字元串
     *
     * @param filePath --->檔案路徑
     * @return
     */
    public static String getImageStr(String filePath) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(filePath);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /*
     * 測試代碼
     */
    public static void main(String[] args) {
        String imageStr = getImageStr("C:\\tempfile\\1629689877969src.pdf");
        System.out.println(imageStr);
        boolean generateImage = generateImage(imageStr, "result.pdf");
        System.out.println(generateImage);
    }


}