如何将文件流转换成byte[]数组

网友投稿 534 2022-11-16

如何将文件流转换成byte[]数组

如何将文件流转换成byte[]数组

目录将文件流转换成byte[]数组将文件转为byte[],通过ByteArrayOutputStream实现通过文件路径转换byte[]将bitmap对象

将文件流转换成byte[]数组

InputStream is = new FileInputStream(new File("D://a.txt"));

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

byte[] bytes = new byhttp://te[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 Bhttp://yteArrayOutputStream();

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;

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:python_把字符串转化为日期
下一篇:pyhton_使用插值法填充缺失值
相关文章

 发表评论

暂时没有评论,来抢沙发吧~