简体   繁体   中英

Write x bytes with value y to a file in java

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

String strFileName = "C:/FileIO/BufferedOutputStreamDemo";
FileOutputStream fos = new FileOutputStream(strFileName);
fos.write(yourbytes);

If you don't want to allocate new array every time, allocate an array that will definitely be big enough for your X, store it somewhere in your class, then, when you need to write it, fill it with Y, and you can specify how many bytes from the array to write in OutputStream.write(byte[] b, int off, int len) method. Also, you don't need DataOutputStream to write bytes, just BufferedOutputStream will suffice.

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