package com.nantian.cloud.jly.vo.util;

import java.io.*;

public class FileUtil {

    /**
     * 将文件转换成byte数组
     * @param
     * @return
     */
    public static byte[] file2byte(File tradeFile){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 文件大小转换
     * @param fileSiz
     * @return
     */
    public static String getFileSize(long fileSiz) {
        Float size = Float.parseFloat(String.valueOf(fileSiz));

        //如果字节数少于1024，则直接以B为单位，否则先除于1024
        if (size < 1024) {
            return  String.valueOf(size)+ "B";
        } else {
            size = size / 1024;
        }

        //如果原字节数除于1024之后，少于1024，则可以直接以KB作为单位
        if (size < 1024) {
            return String.format("%.2f",size) + "KB";
        } else {
            size = size / 1024;
        }

        if (size < 1024) {
            //MB
            return String.format("%.2f",size) + "MB";
        } else {
            //GB
            size = size / 1024;
            return String.format("%.2f",size) + "GB";
        }
    }
}
