无法写入超出特定大小的DataOutputStream - OutOfMemoryError [英] Unable to write into DataOutputStream beyond a specific size - OutOfMemoryError

查看:511
本文介绍了无法写入超出特定大小的DataOutputStream - OutOfMemoryError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码产生OutOfMemory异常:

I have the following code which produces an OutOfMemory exception:

byte[] buf = new byte[10240];
int len = 0;
DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
while ((len = _inputStream.read(buf)) > 0) {
    System.out.println("len : " + len);
    System.out.println("Going to write buf into dataOS : " + buf.length);
    dataOS.write(buf, 0, len);
    System.out.println("dataOS.size() : " + dataOS.size());
}
_inputStream.close();

以下是调试输出的最后几行:

The following is the last few lines from the debug output:

len : 10240
Going to write buf into dataOS : 10240
dataOS.size() : 342804702
len : 10240
Going to write buf into dataOS : 10240
dataOS.size() : 342814942
len : 10240
Going to write buf into dataOS : 10240

当我尝试写入342814942以外的dataOS时会发生异常。

The exception occurs when I try to write into the dataOS beyond 342814942.

可能有人请帮我处理这个?

Could someone please help me handle this?

谢谢!

推荐答案

它有与DataOutputStream无关(它不保留任何数据)以及与底层流有关的所有内容 conn.getOutputStream()。现在,你没有在那里显示相关代码,但我猜猜conn是HttpURLConnection的一个实例。我相信HttpURLConnection的输出流缓冲输出,以便它可以确定输出长度(除非你明确设置它)。如果你知道输出长度,你可以直接使用 HttpURLConnection.setFixedLengthStreamingMode 设置,或者你可以调用 HttpURLConnection.setChunkedStreamMode 允许数据以块的形式发送而不是完全缓存在内存中。

It has nothing to do with the DataOutputStream (which maintains no data whatsoever) and everything to do with your underlying stream conn.getOutputStream(). now, you haven't show the relevant code there, but i'm going to guess "conn" is an instance of HttpURLConnection. i believe the outputstream for HttpURLConnection buffers the output so that it can determine the output length (unless you set it explicitly). if you know the output length, you could set that directly using HttpURLConnection.setFixedLengthStreamingMode, or you could call HttpURLConnection.setChunkedStreamMode to allow the data to be sent in chunks instead of buffered entirely in memory.

将来,当你遇到OOME时,你应该总是生成堆转储并在内存分析器中打开它。几乎总会立即向您显示问题所在(例如在基础流中,不是 DataOutputStream)。

in the future, when you encounter an OOME you should always generate a heap dump and open that in a memory profiler. that will almost always show you immediately where the problem is (e.g. in the underlying stream, not the DataOutputStream).

这篇关于无法写入超出特定大小的DataOutputStream - OutOfMemoryError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆