如何在String中存储大型二进制数据?

时间:2012-07-11 11:17:05

标签: java

  

可能重复:
  OutOfMemoryError : When receiving XML response of 2.3 MB

我从Web服务获得了响应字符串,这是XML格式的大量二进制字符串。我能够将响应数据存储到Object中。但我想解析响应并将其存储到本地数据库中。所以我必须将对象数据转换为String。如果我将对象数据转换为字符串。它出现“记忆问题”。

我的回答是这样的

<xmlstring>
<oneslip>78364</oneslip>
<threeslip>Hello</threeslip>
<twoslip>3</twoslip>
<Binarydata>"Here the large amount of binary data"</Binarydata>

<oneslip>78364</oneslip>
<threeslip>Hello</threeslip>
<twoslip>3</twoslip>
<Binarydata>"Here the large amount of binary data"</Binarydata>

..
..
..

高达50

</xmlstring>

2 个答案:

答案 0 :(得分:0)

尝试StringBuffer

bufferedReader = new BufferedReader(
                     new InputStreamReader(
                         response.getEntity().getContent()));

StringBuffer stringBuffer = new StringBuffer("");
String line = "";
String LineSeparator = System.getProperty("line.separator");

while ((line = bufferedReader.readLine()) != null) {
    stringBuffer.append(line + LineSeparator); 
}

bufferedReader.close();

答案 1 :(得分:0)

如果您的数据库将数据表示为 binary (而不是字符),则使用中间字符串似乎是错误的方法。您可以使用Blob.setBinaryStream获取用于将数据写入db的流。然后,您可以直接从输入流到输出流将事物以可管理的块的形式传输到该流,而无需缓冲整个事物。

如果您想要传输输入流的全部内容,甚至不需要查看它,您甚至可以使用CallableStatement.setBlob(String,InputStream)将BLOB列直接设置为该流中的数据。

如果你必须将东西转换成字符,因为数据库使用clob而不是blob,那么clob也存在类似的方法,你仍然可以避免使用中间字符串。