2016-06-28 35 views
0

我有以下将大型映像写入磁盘的代码。我的应用程序服务器正在运行的内存,我想知道如果我能以某种方式优化如下:优化将字节数组映像写入磁盘的代码

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

CodeReview.stackexchange.com将是一个很好的地方。 – Qix

+1

而不是在内存中有整个字节数组(base64AttachmentInBytes),然后绕着'read'ing循环说8K字节,然后写入它们。即直接使用'ByteArrayInputStream'上的方法而不是'IOUtils' –

+0

请参阅此页上的第一个示例http://www.studytrails.com/java-io/byte-reading-writing.jsp –

回答

0

有你的代码更改:使用IOUtils.copy和你自己控制自己的IO

  1. 避免。
  2. 为您的机箱和机器设置测试不同的IO类。
  3. 按照此链接中提到的基本故障排除步骤进行操作。 http://www.oracle.com/technetwork/articles/javase/perftuning-137844.html

我发现选择一个缓冲大小是重要的,这些技巧是克服内存瓶颈超级有用: 这里是关于如何加快I/O的一些基本规则:

Avoid accessing the disk. 
Avoid accessing the underlying operating system. 
Avoid method calls. 
Avoid processing bytes and characters individually. 
0

我遵循@pvg和@scaryWombat的建议。为了检测mimetype,我停止了整个文件的阅读。然后,我使用iHarder的Base 64解码,并将我的base64符号字符串直接写入文件中。

为了检测mimetype我解码了前100个字符的子字符串。