OutOfMemory when creating Base64 string in java?

后端 未结 4 1696
清酒与你
清酒与你 2021-01-24 07:48

I used ostermillerutils library to create base64 string but I get OutOfMemory error if the image is heavy. If the image I try to convert is a simple image, the code is working f

4条回答
  •  一向
    一向 (楼主)
    2021-01-24 07:59

    If you like to write the encoded content straight into a file then use the following code

    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 class from Apache Commons IO.

    EDIT Since you want to do it using BufferedWriter, use it as follows

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

提交回复
热议问题