1,105,546 Community Members

how to free memory of byte array

Member Avatar
Junior Poster in Training
59 posts since Sep 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 3 [?]
Skill Endorsements: 0 [?]

how to free memory of byte array...


for(int j=0;j<count;j++){

buffer=null; //free the memory by set as a null but not working????? shows array index out of bound exception for the second time
buffer= new byte[size]; //byte mem alloc

temp2=di.read(buffer,total,size);// read buffer

fo= new FileOutputStream(flist[j]);
ds= new DataOutputStream(fo);
System.out.println("write: "+(j+1));


exception occur at run time...

Exception in thread "main" java.lang.IndexOutOfBoundsException
        at java.io.FileInputStream.readBytes(Native Method)
        at java.io.FileInputStream.read(Unknown Source)
        at java.io.DataInputStream.read(Unknown Source)
        at filesplitandjoin.main(filesplitandjoin.java:57)

src code attached:(

Attachments filesplitandjoin.java (1.1KB)
Member Avatar
Posting Maven
2,632 posts since Apr 2010
Reputation Points: 134 [?]
Q&As Helped to Solve: 378 [?]
Skill Endorsements: 17 [?]

You cannot set a null value to a primitive array. You could initialize an array size 0 instead...

buffer = new byte[0];

This mean any previous declaration/used will be marked as garbage. That means the GC (Garbage Collector) will free up the memory whenever it runs.

Member Avatar
Industrious Poster
4,165 posts since Feb 2006
Reputation Points: 1,351 [?]
Q&As Helped to Solve: 510 [?]
Skill Endorsements: 22 [?]
Team Colleague

You cannot set a null value to a primitive array. You could initialize an array size 0 instead...

Uhm, Yes, you can. You cannot assign null to an element of the array but you sure can assign null to the array reference (which is what the OP did).

@OP your problem is that the second argument in your "read" call is the offset into the byte array (that is the first argument) which tells read where to start adding the bytes it reads, and "total" is probably already as large as size making that write beyond the end of the array.

Question Answered as of 2 Years Ago by masijade and Taywin
This question has already been solved: Start a new discussion instead
Start New Discussion
View similar articles that have also been tagged: