所以我有几种方法,当我使用断言测试对它们进行测试时,它失败了,我不能为我的生活找出原因,所以如果有人可以帮助我,我会'我非常欣赏它。
这些方法应该将块写入现有文件,然后读取所述块并确保断言有效。
写入方法:
public void writeBlock(int blockNum, AbstractDBFile f, AbstractBlock b)
throws IOException {
DBFile dbf = (DBFile) f;
Block blk = (Block) b;
if (blockNum >= dbf.totalNumOfBlocks){
dbf.totalNumOfBlocks++;
}
int header = 4096;
RandomAccessFile file = new RandomAccessFile(dbf.fileName, "rw");
file.seek(header + (blockNum) * 4096);
file.write(blk.getData(), 0, 4096);
file.close();
f.curBlockPos = blockNum + 1;
}
阅读方法:
public AbstractBlock readBlock(int blockNum, AbstractDBFile f)
throws IOException {
f.setCurBlockPos(blockNum);
DBFile f2 = new DBFile();
f2.setCurBlockPos(f.getCurBlockPos());
f2.setFileName(f.getFileName());
Block block = new Block();
int currentByte = f2.getCurBlockPos() * 4096;
byte[] data = new byte[4096];
String filename = f2.getFileName();
File ourFile = new File(filename);
RandomAccessFile file = new RandomAccessFile(ourFile, "r");
FileChannel inChannel = file.getChannel();
ByteBuffer bb = ByteBuffer.allocate(currentByte);
inChannel.read(bb);
while(inChannel.read(bb)>0){
bb.flip();
for (int i =0; i<bb.limit(); i++){
data[i]=bb.get();
block.setData(data);
}
bb.clear();
}
inChannel.close();
file.close();
return block;
}
Block Class:
public class Block extends AbstractBlock {
@Override
public byte[] getData() {
// TODO Auto-generated method stub
/*byte[] data = new byte [4096];
data[0] = 10;
data[5] = 20;*/
return data;
}
@Override
public void setData(byte[] d) throws IOException {
int freeByte = -1;
for(int i = 0; i < data.length && freeByte < 0; i++)
if(data[i] == 0)
freeByte = i;
for(int i = freeByte, j = 0; j < d.length; i++, j++)
data[i] = d[j];
}
}
断言测试:
public void testWriteRead() throws IOException {
StorageManager manager = new StorageManager();
DBFile file = (DBFile)manager.createFile("File1");
byte [] write = new byte[4096];
write[0] = 10;
write[5] = 20;
Block block = new Block();
block.setData(write);
manager.writeBlock(0, file, block);
Block b = (Block) manager.readBlock(0, file);
assertTrue(areEqual(write,b.getData()));
}
private boolean areEqual(byte [] array1, byte [] array2) {
if(array1.length != array2.length)
return false;
for(int i = 0 ; i < array1.length ; i++)
if(array1[i] != array2[i])
return false;
return true;
}
如果我不绝望,我不会这样做,任何帮助都会非常感激。