In the following code. I’m reading a file into a small buffer ( len=CHUNK_SIZE) And I simply want to write this buffer to outputstream. But even though i am flushing after every chunk I get an heap overflow exception. Well if I want to stream small files everything is fine. But shouldn’t flush also delete all data in the stream?
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();
}
DataOutputStreamdoesn’t buffer at all, butHttpURLConnection‘s output stream buffers everything by default, so it can set theContent-Lengthheader. Use chunked transfer mode to prevent that.You don’t actually need the DataOutputStream at all here: just write to the connection’s output stream.
Don’t flush() inside the loop either.