我使用 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/22163825/