Android Java OutputStream将整个文件缓冲到流中

问题描述

我有一个应用程序,需要从图库(或从相机应用程序)中加载视频文件到该应用程序,然后将该视频文件发送到HTTP PUT请求到预先签名的S3上传网址。

我的问题是,当我在Android Studio上查看事件探查器时,代码的HTTPURLConnection部分似乎正在占用大量内存。在特定时刻内存使用量的增加等于视频文件的大小,因此我假设整个视频文件字节都已加载到内存中。这是我的代码段以及到目前为止我尝试过的内容。 所有这些试验最终都具有相同的内存使用结果。

    HttpURLConnection connection = (HttpURLConnection) urls[0].openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Content-Type","video/mp4");
    
    BufferedInputStream in =
            new BufferedInputStream(getActivity().getContentResolver()
                                             .openInputStream(uri));
    DataOutputStream out =
            new DataOutputStream(connection.getOutputStream());
    int bufferSize = 8 * 1024;
    byte[] buffer = new byte[bufferSize];
    int len = 0;
    while ((len = in.read(buffer)) != -1) {
       out.write(buffer,len);
       out.flush();
       // After I flush the output stream,shouldn't the out.size() be 0?
       // When I print logs here,the out stream's size keeps growing to the video file's size.
    }

    in.close();
    out.close();

我也尝试过 IOUtils.copyStream(in,out); 我也尝试使用BufferedOutputStream代替DataOutputStream

  1. 从代码中,为什么我一次从输入流中读取8 KB的事实,但我的代码仍将整个文件加载到内存中?
  2. 当我刷新DataOutputStream时,为什么我的OutputStream仍然不是0字节?
  3. 对于超过200MB的大文件,实现此目标的最佳方法是什么?

预先感谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...