package com.ho.filecenter;

import cn.hutool.core.codec.Base64;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.RandomAccessFile;

/**
 * @author fancl
 * @desc:
 * @date 2023/1/5
 */
public class FileRead {
    public static void main(String[] args) {
        String path = "d:/2.png";
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            byte[] bytes = readBlock(path, 0);

            BufferedImage bufferedImage = ImageIO.read(new File(path));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", baos);
            byte[] bytes2 = baos.toByteArray();
            String encode = Base64.encode(bytes);
            String trim2 = encoder.encodeBuffer(bytes).trim();
            System.out.println();
            System.out.println();
        }catch (Exception e){

        }


    }

    //按位置分块读取文件内容
    public static byte[] readBlock(String path, int pointer) throws Exception {
        if (!new File(path).exists()){
            throw new BusinessException(BaseResponseCode.FILE_NOT_EXISTS) ;
        }
        RandomAccessFile raf = new RandomAccessFile(path, "r");
        long length = raf.length();
        System.out.println("文件大小：" + length);
        //设置指针的位置,每次有偏移
        raf.seek(pointer * 102400);
        //每次读取102400字节,这个应该改为参数配置
        byte[] bytes = new byte[102400];
        int readSize = raf.read(bytes);
        //如果没有读到102400个字节，需要做数组拷贝
        //读取时判断是否还有剩余字节
        if (readSize < 102400) {
            byte[] copy = new byte[readSize];
            System.arraycopy(bytes, 0, copy, 0, readSize);
            raf.close();
            return copy;
        }
        raf.close();
        return bytes;
    }
}
