Affichage des articles dont le libellé est ByteArrayOutputStream Out of Memory error when send over socket. Afficher tous les articles
Affichage des articles dont le libellé est ByteArrayOutputStream Out of Memory error when send over socket. Afficher tous les articles

mardi 22 mars 2016

ByteArrayOutputStream Out of Memory error when send over socket

I am writting a app transfer file based Socket.When I transfer file less than 10 mb ,then no matter what happens.But when I transfer file over 20mb, then I get Out of Memory error and crash my app.

This is my code

RandomAccessFile aFile = new RandomAccessFile(path, "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n;
while ((n = inChannel.read(buffer)) > 0) {
        buffer.flip();
        total_length += n;
        baos.write(buffer.array(), 0, n);
        byte[] aaa = baos.toByteArray();
        ObjectStream obstream = new ObjectStream("stream", aaa, session_request, total_length);
        aaa=null;
        outt.writeObject(obstream);
        obstream = null;
        baos.reset();
        buffer.clear(); // do something with the data and clear/compact it.
}
inChannel.close();
aFile.close();

This is error that geted :

FATAL EXCEPTION: Thread-177
java.lang.OutOfMemoryError
at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:122)
at com.jsc.Remote2Droid.Thread.ThreadClientData.run(ThreadClientData.java:705)

out of memory at location:

byte[] aaa = baos.toByteArray();

Please help me fix my code.Thank all.Sorry for my english.



ByteArrayOutputStream Out of Memory error when send over socket