[英]Trouble with saving a 4D array to file
我有一些代碼似乎無法正常運行。 重點是獲取一個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個字節之后的所有內容變為空白?
提前致謝。
你為什么要比較i
對chunkdata.length
當i
與初始化start
? 我認為應該改用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?
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.