Python 官方文档:入门教程 => 点击学习
目录将文件流转换成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();
通过ByteArrayOutputStream实现
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;
}
转为byte[] 并进行Base64压缩
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;
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: 如何将文件流转换成byte[]数组
本文链接: https://lsjlt.com/news/159611.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0