我有以下代码将大图像写入磁盘。我的应用程序服务器内存不足,我想知道我是否能以某种方式优化以下内容:
public void writeImgToDisk(byte[] base64AttachmentInBytes, String dmxi){
String destinationAndFileName = "";
String fileNameMinusExtension = getCurrentTimeStampForFileNaming();
String extension="";
try {
TikaConfig config = TikaConfig.getDefaultConfig();
InputStream stream = new ByteArrayInputStream(base64AttachmentInBytes);
MediaType mediaType = config.getMimeRepository().detect(stream, new Metadata());
MimeType mimeType;
try {
mimeType = config.getMimeRepository().forName(mediaType.toString());
extension = mimeType.getExtension();
System.out.println("Extension is:"+ extension);
File folder = new File("Z:\\images\\"+ sref);
if (!folder.exists()){
folder.mkdir();
}
destinationAndFileName = "Z:\\images\\"+ dmxi + "\\" + fileNameMinusExtension+ extension;
System.out.println("destinationAndFileName is:"+ destinationAndFileName);
} catch (MimeTypeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream input = new ByteArrayInputStream(base64AttachmentInBytes);
OutputStream output = new FileOutputStream(destinationAndFileName);
IOUtils.copy(input, output);
System.out.println("It was written..");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这有效,但它是高音量通话时瓶颈的原因。
答案 0 :(得分:0)
您的代码有变化:
我发现选择缓冲区大小很重要,这些提示对克服内存瓶颈非常有用: 这里有一些关于如何加速I / O的基本规则:
Avoid accessing the disk.
Avoid accessing the underlying operating system.
Avoid method calls.
Avoid processing bytes and characters individually.
答案 1 :(得分:0)
我遵循了@pvg和@scaryWombat给出的建议。我停止阅读整个文件,以便检测mimetype。然后我使用iHarder的Base 64解码并将我的base64表示法字符串直接写入文件中。
为了检测mimetype我解码了前100个字符的子串。