如何將文件流轉(zhuǎn)換成byte[]數(shù)組
更新時間:2021年12月10日 14:45:35 作者:走馬川行雪
這篇文章主要介紹了如何將文件流轉(zhuǎn)換成byte[]數(shù)組,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
將文件流轉(zhuǎn)換成byte[]數(shù)組
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); } //轉(zhuǎn)換后的byte[] byte[] finalBytes = outputStream.toByteArray();
將文件轉(zhuǎn)為byte[],通過ByteArrayOutputStream實現(xiàn)
通過文件路徑轉(zhuǎn)換byte[]
通過ByteArrayOutputStream實現(xiàn)
/** * 將文件轉(zhuǎn)為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對象
轉(zhuǎn)為byte[] 并進(jìn)行Base64壓縮
/** * bitmap轉(zhuǎn)為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; }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot配置Swagger的實現(xiàn)代碼
這篇文章主要介紹了Spring Boot配置Swagger的實現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12springboot+springJdbc+postgresql 實現(xiàn)多數(shù)據(jù)源的配置
本文主要介紹了springboot+springJdbc+postgresql 實現(xiàn)多數(shù)據(jù)源的配置,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09Java編程synchronized與lock的區(qū)別【推薦】
互聯(lián)網(wǎng)信息泛濫環(huán)境下少有的良心之作!如果您想對Java編程synchronized與lock的區(qū)別有所了解,這篇文章絕對值得!分享給大家,供需要的朋友參考。不說了,我先學(xué)習(xí)去了。2017-10-10Spring AOP的幾種實現(xiàn)方式總結(jié)
本篇文章主要介紹了Spring AOP的幾種實現(xiàn)方式總結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02