加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

从Uri读取inputStream并通过outputStream android发送的问题

发布时间:2020-12-15 02:30:27 所属栏目:Java 来源:网络整理
导读:美好的一天,我试图通过OutputStream从SDCard发送文件.我打算从我拥有的文件名中获取URI,然后使用InputStream读取URI并转换为其他发送的字节.目前代码卡在get InputStream中(如下所述),没有任何反应. 此外,我不知道我是否正确使用URI来获取要发送的文件的实际
美好的一天,我试图通过OutputStream从SDCard发送文件.我打算从我拥有的文件名中获取URI,然后使用InputStream读取URI并转换为其他发送的字节.目前代码卡在get InputStream中(如下所述),没有任何反应.

此外,我不知道我是否正确使用URI来获取要发送的文件的实际路径.

请大家多多感激之情,因为我已经被困在这里一段时间了.谢谢.

我的代码:

public void sendFile() {
    Log.d(TAG,"sending data");
    InputStream inputStream = null;
    String filePath = Environment.getExternalStorageDirectory()
          .toString() + "/" + files.get(0);
    Log.d(TAG,"filepath is" + filePath);

    Uri uri = Uri.parse(filePath);

    Log.d(TAG,"obtained input stream here in Activity");
    Log.d(TAG,"Uri here is" + uri);  // nothing happens after here,Basically stuck!!
    try {
        inputStream = getContentResolver().openInputStream(uri);
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        Log.d(TAG,"obtained input stream here in Activity");

        int buffersize = 1024;
        byte[] buffer = new byte[buffersize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer,len);
        }

        AppServices.write(byteBuffer.toByteArray());

    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

解决方法

使用 :

Uri uri = Uri.fromFile(new File(filePath));

或者只是使用:

inputStream  = new FileInputStream(filePath);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读