将 4D 阵列保存到文件时出现问题



我有一些代码似乎没有按照应有的方式运行。重点是取一个 256x128x256x2 的整数数组,将其拆分为 256 个 16x128x16x2 块,将块处理成一个字节数组,然后将该字节数组添加到要保存的主字节数组中。 保存前chunkdata[]很好,但保存后,除了前 4096 个字节外,整个文件都是空白的。位置表(文件中每个块的位置)在那里,前四个字节的"块头"在那里,其他一切都是0,这不应该发生。

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);
    }
}

因此,假设 putChunk 和 getChunk 按预期工作,以及我可怕的算法,是什么会导致超过前 4096 个字节的所有内容都是空白的?

提前谢谢。

istart初始化时,为什么要将ichunkdata.length进行比较?我认为应该使用counter

当前:

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

相反,你想写这样的东西:

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

或更紧凑的方式:

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

最新更新