DataOutputStream在内部保存整个缓冲区?

时间:2012-11-18 22:04:33

标签: java stream applet

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

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();                             
 }

1 个答案:

答案 0 :(得分:3)

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

这里根本不需要DataOutputStream:只需写入连接的输出流。

也不要在循环内冲洗()。