package com.tofly.common.service.impl;

import com.tofly.common.core.util.io.IOUtil;
import com.tofly.common.service.CommonFileService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * @author tuonbed
 * @date 2020/4/1  13:24
 */
@Service
@Slf4j
public class CommonFileServiceImpl implements CommonFileService {
    @Override
    @SneakyThrows
    public byte[] getFileByte(String fileName) {
        File f=new File(IOUtil.TEMP_FILEPATH+fileName);
        if(f==null || !f.exists()){
            throw new IOException(fileName+"文件不存在");
        }
        byte[] flieByte=null;
        InputStream in=null;
        try {in = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int size = 0;
            byte[] buf = new byte[10240];
            while ((size = in.read(buf)) > 0) {
                out.write(buf, 0, size);
                out.flush();
            }
            flieByte = out.toByteArray();
        }catch (IOException e){
            log.error(e.getMessage());
        }
        finally {
            try{
                in.close();
            }catch (IOException e){

            };
        }
        return flieByte;
    }

}
