日期:2014-05-20 浏览次数:20871 次
import java.io.IOException;
import java.io.RandomAccessFile;
public class CustomFile {
public static class FileBlock{
short type;
short id;
int offset;
int length;
public short getType() {
return type;
}
public short getId() {
return id;
}
public int getOffset() {
return offset;
}
public int getLength() {
return length;
}
}
private int numberOfBlocks;
private FileBlock[] fileBlocks;
private RandomAccessFile file;
public CustomFile(String fileName) throws IOException{
file = new RandomAccessFile(fileName, "r");
readHeader();//预读文件的数据分配表
}
private void readHeader() throws IOException {
byte[] buffer = new byte[12];
if(2!=file.read(buffer, 0, 2)){
throw new IllegalStateException("读取数据出错");
}
numberOfBlocks = (buffer[0]&0xFF)<<8
------解决方案--------------------
(buffer[1]&0xFF);
if(numberOfBlocks<0
------解决方案--------------------
file.length()<(numberOfBlocks*12+2)){
throw new IllegalStateException("读取文件头数据出错");
}
fileBlocks = new FileBlock[numberOfBlocks];
for(int i=0;i<fileBlocks.length;i++){
FileBlock ff = new FileBlock();
if(12!=file.read(buffer)){
throw new IllegalStateException("读取数据出错");
}
ff.type = (short)((buffer[0]&0xFF)<<8
------解决方案--------------------
(buffer[1]&0xFF));
ff.id = (short)((buffer[2]&0xFF)<<8
------解决方案--------------------
(buffer[3]&0xFF));
ff.offset = (buffer[4]&0xFF)<<24
------解决方案--------------------
(buffer[5]&0xFF)<<16
------解决方案--------------------
(buffer[6]&0xFF)<<8
------解决方案--------------------
(buffer[7]&0xFF);
ff.length = (buffer[8]&0xFF)<<24
------解决方案--------------------
(buffer[9]&0xFF)<<16
------解决方案--------------------
(buffer[10]&0xFF)<<8
------解决方案--------------------
(buffer[11]&0xFF);
fileBlocks[i] = ff;
}
}
/**
* 返回小数据量时可以使用,大数据量时需要另行编写代码。