简体   繁体   中英

java.lang.OutOfMemoryError for writing of InputStream in FileOutputStream

I can not understand, what I do wrong:

public static void writeToFile(InputStream inputStream, File file) throws IOException, FileNotFoundException {
    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
    try {
        int size = 1024 * 1024;
        byte[] buf = new byte[size];
        int byteRead;
        while ((byteRead = inputStream.read(buf)) > 0) {
            outputStream.write(buf, 0, byteRead);
        }
        outputStream.close();
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Exception:

6157-6185/com.wiserep E/AndroidRuntime﹕ FATAL EXCEPTION:
IntentService[SynchronizationService] java.lang.OutOfMemoryError
    at java.lang.String.<init>(String.java:432)
    at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:642)
    at java.lang.StringBuffer.toString(StringBuffer.java:723)
    at com.splunk.mint.network.io.InputStreamMonitor.updateBody(InputStreamMonitor.java:104)
    at com.splunk.mint.network.io.InputStreamMonitor.read(InputStreamMonitor.java:71)
    at com.wiserep.web.HttpTransport$HttpHelper.writeToFile(HttpTransport.java:196)    

libraries:

  • import android.util.Log;
  • import org.apache.http.NameValuePair;
  • import javax.net.ssl.*;
  • import java.io.*;
  • import java.net.*;
  • import java.security.cert.X509Certificate;
  • import java.text.SimpleDateFormat;
  • import java.util.Date;
  • import java.util.List; import java.util.Locale;

You are using Splunk Mint to monitor the application. The bug is in the code from Splunk: it tries to create a string with the entire contents of the stream, who knows what for, and this is what causes the app to run out of memory. There has to be a way to limit the size of the part of the stream that Splunk Mint captures, or disable this particular feature completely.

Maybe the cause it's that you are requesting chunks of memory too big and the phone doesn't have any contiguous block big enough to allocate it, that's why it's giving Outofmemoryerror. Try to lower the chunk size

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM