码迷,mamicode.com
首页 > 编程语言 > 详细

Java获取文件的byte数组数据

时间:2020-02-29 00:18:21      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:get   buffer   return   获取文件   could not   null   stack   row   getname   

public static byte[] getFileByteArray(File file) {
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        byte[] buffer = null;
        try (FileInputStream fi = new FileInputStream(file)) {
            buffer = new byte[(int) fileSize];
            int offset = 0;
            int numRead = 0;
            while (offset < buffer.length
                    && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
                offset += numRead;
            }
            // 确保所有数据均被读取
            if (offset != buffer.length) {
                throw new IOException("Could not completely read file "
                        + file.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer;
    }

  

Java获取文件的byte数组数据

标签:get   buffer   return   获取文件   could not   null   stack   row   getname   

原文地址:https://www.cnblogs.com/toSeeMyDream/p/12381183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!