我是靠谱客的博主 辛勤信封,最近开发中收集的这篇文章主要介绍如何将文件流转换成byte[]数组,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

将文件流转换成byte[]数组

InputStream is = new FileInputStream(new File("D://a.txt")); 
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int temp;
while ((temp = is.read(bytes)) != -1) {
     outputStream.write(bytes, 0, temp);
}
//转换后的byte[]
byte[] finalBytes = outputStream.toByteArray();

将文件转为byte[],通过ByteArrayOutputStream实现

通过文件路径转换byte[]

通过ByteArrayOutputStream实现

/**
     * 将文件转为byte[]
     * @param filePath 文件路径
     * @return
     */
    public static byte[] getBytes(String filePath){
        File file = new File(filePath);
        ByteArrayOutputStream out = null;
        try {
            FileInputStream in = new FileInputStream(file);
            out = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int i = 0;
            while ((i = in.read(b)) != -1) {
            out.write(b, 0, b.length);
            }
            out.close();
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] s = out.toByteArray();
        return s;
    }

将bitmap对象

转为byte[] 并进行Base64压缩

/**
     * bitmap转为base64
     * 
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是辛勤信封为你收集整理的如何将文件流转换成byte[]数组的全部内容,希望文章能够帮你解决如何将文件流转换成byte[]数组所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(170)

评论列表共有 0 条评论

立即
投稿
返回
顶部