我正在编写一个程序,要求我编写和回读我创建的对象。当我试图回读对象并反序列化它时,我得到 Ilegal表达式错误。我想知道是否有人能告诉我这是怎么解决的。
RandomAccessFile temp = new RandomAccessFile(fileSystemName,"r");
this.numberOfDirectories= temp.readInt();
this.fileSystemSize = temp.readInt();
this.numberOfBlocks = temp.readInt();
//Prepares and loads the bitMap
numberOfBytes = (numberOfBlocks/8)+1;
//directory = new Directory(numberOfDirectories);
bitMap = new byte[numberOfBytes];
for(int i=0;i<numberOfBytes;i++)bitMap[i]=temp.readByte();
temp.close();
FileInputStream fin = new FileInputStream(fileSystemName);
ObjectInputStream ois = new ObjectInputStream(fin);
//File file = new File(fileSystemName);
System.out.println(bitMap.length);
offset = 12 + numberOfBytes;
//ois.skipBytes(offset);
//Read Directories
directory = <Directory> ois.readObject();
偏移是因为我首先使用RandomAccessFile对象首先读取一些整数和字符。我很感激帮助。感谢
答案 0 :(得分:0)
您必须以可比较的方式阅读数据,并按照您的编写方式阅读。
对象流具有特定格式。它有一个标题,它在你感兴趣的字节周围丢失了字节。如果你写一个Integer
,它将需要88个字节。你不能只是在一个Object流中读取并随机访问它的位或跳过字节期望它能够工作。
你是怎么写数据的?
答案 1 :(得分:0)
我会使用一个流然后你不需要担心抵消,并确保你正在阅读你正在写的东西。例如,以下工作正常:
final String name = "tmp.data";
int numberOfDirectories = 2;
int fileSystemSize = 4;
byte[] bitMap = new byte[] { 0, 1, 0 };
File someObject = new File(".");
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(name));
outputStream.write(numberOfDirectories);
outputStream.write(fileSystemSize);
outputStream.write(bitMap.length);
outputStream.write(bitMap);
outputStream.writeObject(someObject);
outputStream.close();
// ....
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(name));
System.out.println("numberOfDirectories:" + inputStream.read());
System.out.println("fileSystemSize:" + inputStream.read());
final int size = inputStream.read();
byte[] readBitMap = new byte[size];
inputStream.read(readBitMap);
System.out.println("bitMap:" + readBitMap);
System.out.println("someObject:" + inputStream.readObject());
inputStream.close();
此外,为了让生活更轻松,我很想创建一个代表您要存储在文件中的所有数据的类,然后Object流为您处理所有事情:
public static class Data {
private int numberOfDirectories;
private int fileSystemSize;
private byte[] bitMap;
private File someObject;
// getters and setters ....
}
final String name = "tmp.data";
Data data = new Data();
data.setNumberOfDirectories(2);
data.setFileSystemSize(4);
data.setBitMap(new byte[] { 0, 1, 0 });
data.setSomeObject(new File("."));
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(name));
outputStream.writeObject(data);
outputStream.close();
// ....
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(name));
Data readData = (Data) inputStream.readObject();
System.out.println("numberOfDirectories:" + readData.getNumberOfDirectories());
System.out.println("fileSystemSize:" + readData.getFileSystemSize());
System.out.println("bitMap:" + readData.getBitMap());
System.out.println("someObject:" + readData.getSomeObject());
inputStream.close();