android - 如何将文件转换为 byte[] 数组以通过 Android 中的蓝牙套接字发送?

标签 android

美好的一天,我有一个要求,我需要通过蓝牙套接字连接发送文件(图像/视频等)。我使用 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/

相关文章:

java - 调用 fragment 并传递参数

android - 是否可以直接从 SQLite 读取联系人列表

android - Android在哪里保存属性

android - 如何将 Object[] 转换为 String[ ]

android - 当我使用谷歌地图时生成签名的 apk 时出错?

java - 从 fragment 替换 fragment 时 onRequestPermissionsResult 回调不起作用

java - 从android中的linikedList中删除项目

android - 广播接收器和未决 Intent : Show a toast

重启期间主屏幕启动器应用程序不会调用 Android 应用程序 onCreate

java - 为什么我的 PipedOutputStream 死锁了?