将File或者InputStream转成byte数组

package com.yinhai.demo.utils;

import java.io.*;

/**
 * 将File或者InputStream转成byte数组
 *
 * Created by Blossom on 2018/7/28.
 */
public class FileUtil {

    public static byte[] File2byte(String filePath) throws Exception {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            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;
    }

    public static byte[] inputStreamToByte(InputStream is) throws Exception{
        BufferedInputStream bis = new BufferedInputStream(is);
        byte [] a = new byte[1000];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = bis.read(a))!=-1){
            bos.write(a, 0, len);
        }
        bis.close();
        bos.close();
        return bos.toByteArray();
    }

}

猜你喜欢

转载自blog.csdn.net/blossomfzq/article/details/83027030