首页 > 其他 > 详细

通过文件路径获得对象

时间:2016-04-20 11:13:44      阅读:306      评论:0      收藏:0      [点我收藏+]

    // 读取文件路径转换成byte[]类型
    private static byte[] getBytes(String str) throws IOException {
        byte[] bytes = null;
        if (str != null || !str.equals("")) {
            File file = new File(str);
            InputStream is = new FileInputStream(file);
            int length = (int) file.length();
            if (length > Integer.MAX_VALUE) // 当文件的长度超过了int的最大值
            {
                System.out.println("路径过长!!");
                return null;
            }
            bytes = new byte[length];
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                    && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            // 如果得到的字节长度和file实际的长度不一致就可能出错了
            if (offset < bytes.length) {
                System.out.println("字符长度图实际长度不一致");
                return null;
            }
            is.close();
        }
        return bytes;
    }

通过文件路径获得对象

原文:http://www.cnblogs.com/lzw0414/p/5411531.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!