如何將文件流轉(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[] 并進行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)文章
elasticsearch通過guice注入Node組裝啟動過程
這篇文章主要為大家介紹了?elasticsearch通過guice注入Node組裝啟動過程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04
Java中使用MongoDB數(shù)據(jù)庫實例Demo
MongoDB是由C++語言編寫的,基于分布式文件存儲的數(shù)據(jù)庫,是一個介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品,是最接近于關(guān)系型數(shù)據(jù)庫的NoSQL數(shù)據(jù)庫,下面這篇文章主要給大家介紹了關(guān)于Java中使用MongoDB數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2023-12-12

