美好的一天,我有一个要求,我需要通过蓝牙套接字连接发送文件(图像/视频等)。我使用 SDK 中的蓝牙聊天示例作为指导。我可以成功连接,但无法将 sdcard 中的文件转换为字节数组,因此我可以通过 outputStream 写入它。
我可以使用以下代码转换图像:
//After getting the imageId from the cursor object
Bitmap bitmap = Media.getBitmap(getContentResolver(), imageUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
bytes[] bytes = baos.toByteArray();
但是在转换视频或其他文件时遇到问题,我应该使用 ObjectOutputStream 进行所有转换,还是有其他方法可以做到这一点,因为我似乎无法将 fileOutputStream 转换为字节数组?谢谢
最佳答案
使用 getContentResolver().openInputStream(uri)
从 URI 获取 InputStream。然后从输入流中读取数据,将数据转换为输入流中的 byte[]
试试下面的代码
public byte[] readBytes(Uri uri) throws IOException {
// this dynamically extends to take the bytes you read
InputStream inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
关于android - 如何将文件转换为 byte[] 数组以通过 Android 中的蓝牙套接字发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8614641/