首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java把一个资料转化为byte字节

2013-08-16 
java把一个文件转化为byte字节/** * 把一个文件转化为字节 ** @param file * @return byte[] * @throws Ex

java把一个文件转化为byte字节

/** * 把一个文件转化为字节 *  * @param file * @return byte[] * @throws Exception */public static byte[] getByte(File file) throws Exception {byte[] bytes = null;if (file != null) {InputStream is = new FileInputStream(file);int length = (int) file.length();if (length > Integer.MAX_VALUE) // 当文件的长度超过了int的最大值{System.out.println("this file is max ");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("file length is error");return null;}is.close();}return bytes;}

?

热点排行