I am trying to write to a file certain number of bytes lets say x bytes, with a value y. The problem is that i am doing it lots of time and I am currently using DataOutputStream with BufferedOutputStream and the write method that gets an array of byte. Each time i allocate a new array of bytes of length x and write it. It is wasteful and I wonder if there is a more efficient way?
Thanks.
Edit: I have implemented it by allocating a big array that grows by demand, but the problem is that i store it and it might get very big.
The code:
byte[] block = new byte[4096];
try {
for(int i=0; i<nameOccurence.length; ++i){
if(nameOccurence[i] >= block.length){
int size = ((Integer.MAX_VALUE - nameOccurence[i]) <= 0.5*Integer.MAX_VALUE) ? Integer.MAX_VALUE : (nameOccurence[i] * 2);
block = new byte[size];
}
if(nameOccurence[i] == 0){
namePointer[i] = -1;//i.e. there are no vertices with this name
continue;
}
namePointer[i] = byteCounter;
ds.writeInt(nameOccurence[i]);
ds.write(block, 0, nameOccurence[i]*2);
ds.write(block, 0, nameOccurence[i]*2);
byteCounter += (4*((long)nameOccurence[i]))+4;//because we wrote an integer.
}
where ds is DataOutputStream. Please note that the array block can grow till max int if the nameOccurence[i] is large enough.
I think that the best way is to find the max number upon all i in nameOccurence and allocate array of this length. The problem is that it can get Integer.MAX_VALUE.
Maybe it will be better to run with a loop and write 1 byte each time? please note that the underlying of DataOuputStream is BufferedOutputStream.
Use