如何將文件流轉換成byte[]數組
更新時間:2021年12月10日 14:45:35 作者:走馬川行雪
這篇文章主要介紹了如何將文件流轉換成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; }
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
springboot+springJdbc+postgresql 實現多數據源的配置
本文主要介紹了springboot+springJdbc+postgresql 實現多數據源的配置,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09Java編程synchronized與lock的區(qū)別【推薦】
互聯網信息泛濫環(huán)境下少有的良心之作!如果您想對Java編程synchronized與lock的區(qū)別有所了解,這篇文章絕對值得!分享給大家,供需要的朋友參考。不說了,我先學習去了。2017-10-10