如何将文件流转换成byte[]数组
目录
- 将文件流转换成byte[]数组
- 将文件转为byte[],通过ByteArrayOutputStream实现
- 通过文件路径转换byte[]
- 将bitmap对象
将文件流转换成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; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)