gpt4 book ai didi

java - 在java中创建Base64字符串时内存不足?

转载 作者:行者123 更新时间:2023-12-02 02:39:48 25 4
gpt4 key购买 nike

我使用 ostermillerutils 库创建 base64 字符串,但如果图像很重,则会出现 OutOfMemory 错误。如果我尝试转换的图像是简单图像,则代码工作正常。

public String createBase64String(InputStream in) {
//collect = new ByteArrayOutputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for(int readNum; (readNum = in.read(buf)) != -1; ) {
bos.write(buf, 0, readNum);
}
}
catch (IOException ex) {
Logger.getInstance().debug("XML createBase64String: IOException");
return null;
}
finally {
if (in != null) {
try {
in.close();

}
catch (IOException ex) {
;
}
}
}
byte[] ba = bos.toByteArray();
String coded = Base64.encodeToString(ba);
return coded;
}

我也尝试这样做,但是当我尝试解码它时,base64 不正确。

public void createBase64String(InputStream in) throws IOException {
//collect = new ByteArrayOutputStream();

byte[] buf = new byte[1024];
int readNum = 0;

try {
while((readNum = in.read(buf)) != -1)
{
smtp.addBase64(Base64.encodeBase64String(buf));
}
}
catch (IOException ex) {
Logger.getInstance().debug("XML createBase64String: IOException");
}
finally {
if (in != null) {
in.close();
}
}

}

请为 JDK 1.4 以及更高版本的 Java 提出解决方案。

最佳答案

如果您想将编码内容直接写入文件,请使用以下代码

public void encode(File file, OutputStream base64OutputStream) {
InputStream is = new FileInputStream(file);
OutputStream out = new Base64OutputStream(base64OutputStream)
IOUtils.copy(is, out);
is.close();
out.close();
}

IOUtils 来自 Apache Commons IO 的类。

编辑由于您想使用 BufferedWriter 来完成此操作,请按如下方式使用它

 OutputStream out = Base64OutputStream(smtpSocket.getOutputStream()); 
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
IOUtils.copy(is, bw);

关于java - 在java中创建Base64字符串时内存不足?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57185146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com