使用JAVA将File文件转换为byte[]数组

来源:互联网 发布:工作证在线生成软件 编辑:程序博客网 时间:2024/05/20 22:31


// 返回一个byte数组public static byte[] getBytesFromFile(File file) throws IOException {InputStream is = new FileInputStream(file);// 获取文件大小 long lengths = file.length();System.out.println("lengths = " + lengths);if (lengths > Integer.MAX_VALUE) {// 文件太大,无法读取throw new IOException("File is to large "+file.getName());}// 创建一个数据来保存文件数据byte[] bytes = new byte[(int)lengths];// 读取数据到byte数组中int offset = 0;int numRead = 0;while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {offset += numRead;}// 确保所有数据均被读取if (offset < bytes.length) {throw new IOException("Could not completely read file "+file.getName());}// Close the input stream and return bytesis.close();return bytes;}


                                             
0 0