【问题标题】:DataOutputStream internally saving whole buffer?DataOutputStream 在内部保存整个缓冲区?
【发布时间】:2012-11-18 22:04:32
【问题描述】:

在下面的代码中。我正在将文件读入一个小缓冲区(len=CHUNK_SIZE),我只是想将此缓冲区写入输出流。但即使我在每个块之后都刷新,我得到一个堆溢出异常。好吧,如果我想流式传输小文件,一切都很好。但是flush不应该也删除流中的所有数据吗?

URL url = new URL(built);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
//con.setChunkedStreamingMode(CHUNK_SIZE);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary="
                                + Boundary);

FileInputStream is = new FileInputStream(m_FileList.get(i));
DataOutputStream os = new DataOutputStream(con.getOutputStream());

 // .....

 while((read = is.read(temp, 0, CHUNK_SIZE)) != -1) {
      bytesTotal += read;

      os.write(temp, 0, read); // heap overflow here if the file is to big
      os.flush();                             
 }

【问题讨论】:

    标签: java stream applet


    【解决方案1】:

    DataOutputStream 根本不缓冲,但HttpURLConnection 的输出流默认缓冲所有内容,因此它可以设置Content-Length 标头。使用分块传输模式来防止这种情况发生。

    您实际上根本不需要 DataOutputStream:只需写入连接的输出流即可。

    也不要在循环内flush()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 2012-10-24
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      相关资源
      最近更新 更多