jocopa3
jocopa3

Reputation: 796

Trouble with saving a 4D array to file

I have some code that does not seem to operate the way it should. The whole point is to take a 256x128x256x2 array of integers, split it into 256 16x128x16x2 chunks, process the chunks into a byte array, then add that byte array to a main array of bytes to be saved. chunkdata[] is fine before saving, but after saving the whole file is blank except the first 4096 bytes. the location table (location of each chunk in the file) is there and the first four byte "chunk header" is there, everything else is 0's, which isn't supposed to happen.

public void createFile(int[][][][] map){
    byte[] file = new byte[fileLength]; //22,024,192 bytes long
    System.arraycopy(Sector.locationTable, 0, file, 0, Sector.locationTable.length); //This works as it should
    for(int cx = 0; cx < 16; cx++)
    {
        for(int cz = 0; cz < 16; cz++)
        {
            int start = sectorLength+cx*(sectorLength*chunkSectorLength)+cz*(chunkRows*sectorLength*chunkSectorLength); //this algorithm works, just rather hideous 
            int[][][][] chunk = getChunk(map, cx * 16, cz * 16); //This works as it should
            byte[] chunkdata = putChunk(chunk); //The data from this is correct

            int counter = 0;
            for(int i=start;i<chunkdata.length;i++){
                file[i]=chunkdata[counter]; //Data loss here?
                counter++;
            }
        }
    }
    System.out.println("Saving file...");
    writeFile(file, fileLocation);
}

public static void writeFile(byte[] file,String filename){
    try{
        FileOutputStream fos = new FileOutputStream(filename);
        fos.write(file);
        fos.close();
        Messages.showSuccessfulSave();
    }catch(Exception ex){
        Messages.showFileSavingError(ex);
    }
}

So, assuming putChunk and getChunk work as intended, and my hideous algorithms, what could cause everything past the first 4096 bytes to be blank?

Thanks in advance.

Upvotes: 0

Views: 183

Answers (1)

Yogendra Singh
Yogendra Singh

Reputation: 34367

Why are you comparing i against chunkdata.length when i is initialized with start? I think counter should be used instead.

Current:

   int counter = 0;
   for(int i=start;i<chunkdata.length;i++){
      file[i]=chunkdata[counter]; //Data loss here?
      counter++;
   }

Instead, you want to write something like this:

   int counter = 0;
   for(int i=start;counter<chunkdata.length;i++){
       file[i]=chunkdata[counter]; //Data loss here?
       counter++;
   }

or more compact way:

   for(int i=start,counter = 0;counter<chunkdata.length;i++,counter++){
       file[i]=chunkdata[counter]; //Data loss here?
   }

Upvotes: 1

Related Questions