欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2022-04-26 09:08:11|栏目:JAVA代码|点击:

将文件流转换成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;
    }

上一篇:Spring HandlerInterceptor实现原理代码解析

栏    目:JAVA代码

下一篇:Spring Boot实现文件上传示例代码

本文标题:如何将文件流转换成byte[]数组

本文地址:http://www.codeinn.net/misctech/200263.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有