Note that there are some explanatory texts on larger screens.

plurals
  1. POWrite x bytes with value y to a file in java
    primarykey
    data
    text
    <p>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.</p> <p>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:</p> <pre><code> byte[] block = new byte[4096]; try { for(int i=0; i&lt;nameOccurence.length; ++i){ if(nameOccurence[i] &gt;= block.length){ int size = ((Integer.MAX_VALUE - nameOccurence[i]) &lt;= 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. } </code></pre> <p>where ds is DataOutputStream. Please note that the array block can grow till max int if the nameOccurence[i] is large enough.</p> <p>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.</p> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload