2012-10-15 62 views
0

我有一些代碼似乎並不像應該那樣操作。整個過程是取一個256x128x256x2的整數數組,將其分成256個16x128x16x2塊,將塊處理成一個字節數組,然後將該數組添加到要保存的主字節數組中。 chunkdata[]在保存前是好的,但保存後除了第一個4096字節外,整個文件是空白的。位置表(每個塊在文件中的位置)在那裏,前四個字節「塊頭」在那裏,其他的都是0,這不應該發生。將4D陣列保存到文件時遇到問題

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個字節爲空?

在此先感謝。

+0

對不起,忘了提,這是喪失數據。例如,如果x = 16且z = 32,則由於某種原因返回大數組0。 – jocopa3

+0

這看起來應該起作用。你確定問題不在別處或數據中嗎? – Keppil

+0

不完全肯定是誠實的。我知道數據是正確的,因爲我定期打印出格式化後的小樣本。我想在hole中做的事情是將數據拆分爲16x128x16x2的元素塊,將其與其他數據一起處理成byte []數組,然後將其保存到文件中。字節數組中的數據是正確的,但保存數據全部爲0,超過了第一個塊的標題。除了這個之外,我會用最可能有問題的部分更新帖子。 – jocopa3

回答

1

爲什麼當ichunkdata.length比較istart初始化?我認爲應該使用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? 
    } 
+0

非常感謝!在十六進制編輯器中檢查文件後,它保存正確。我想我忽略了那個循環太多以至於沒有注意到這個問題! – jocopa3

+0

很好,知道它的工作。有時你需要第二雙眼睛來找到一個非常微不足道的問題:) –