JAVA将文件转换成byte数组(byte[])

 

 

 /**
     * 将文件转换成byte数组
     * @param filePath  文件File类 通过new File(文件路径)
     * @return byte数组
     */
    public static byte[] File2byte(File filePath) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(filePath);
            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;
    }

 

posted @ 2021-06-22 16:13  yvioo  阅读(5656)  评论(0编辑  收藏  举报