package com.ho.common.tools.util;

import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @Description 字节数据处理工具类
 * Author yule
 * Date 2022/11/9 16:27
 */
@Slf4j
@Component
public class CommonBytesUtil {


    //获取文件大小
    public long getFileSize(String path) {
        if (!new File(path).exists()){
            throw new BusinessException(BaseResponseCode.FILE_NOT_EXISTS) ;
        }
        try {
            RandomAccessFile raf = new RandomAccessFile(path, "r");
            long length = raf.length();
            raf.close();
            return length;
        } catch (FileNotFoundException e) {
            return 0;
        }catch (IOException e){
            log.error(e.getMessage());
        }
        return 0;

    }

    //按位置分块读取文件内容
    public byte[] readBlock(String path, int pointer) throws Exception {
        File file = new File(path);
        if (!file.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);
        //每次读取10485760字节(10M),这个应该改为参数配置
        byte[] bytes = new byte[(int) length];
        int readSize = raf.read(bytes);
        //如果没有读到102400个字节，需要做数组拷贝
        //读取时判断是否还有剩余字节
        if (readSize < length) {
            byte[] copy = new byte[readSize];
            System.arraycopy(bytes, 0, copy, 0, readSize);
            raf.close();
            return copy;
        }
        raf.close();
        return bytes;
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    public  String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

}
