如何将文件流转换成byte[]数组
作者:走马川行雪
这篇文章主要介绍了如何将文件流转换成byte[]数组,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
将文件流转换成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; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。