因此,我正在使用随机访问文件为学校项目创建游戏数据库。我很确定我已经掌握了基础知识并重新阅读了一百万次代码,我似乎无法找到正确读取随机访问文件字节的错误。我计算了每个字的值多次加倍检查......
我的主要方法:
public static void main(String[] args) {
RAFProcessing raf = new RAFProcessing();
try {
RandomAccessFile file = new RandomAccessFile(new File(
"src/FirstTry/database.txt"), "rw");
raf.writeRecord("Fifa", "EA", 2001, file);
raf.readRecord(file);
file.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
在中间写入数据+字节:
public void writeRecord(String gameName, String publisher, int year, RandomAccessFile file) throws IOException
{
Long fileSize = file.length();
file.seek(fileSize);
file.writeUTF(gameName);
for(int loop=0; loop<20-gameName.length(); loop++ )
{
file.writeByte(20);
}
file.writeUTF(publisher);
for(int loop=0; loop<20-publisher.length(); loop++ )
{
file.writeByte(20);
}
file.writeInt(year);
}
Vale of SIZE为48(22 + 22 + 4)
读取数据和字节:
public void readRecord(RandomAccessFile file) throws IOException
{
file.seek(0);
String wholeRecord ="";
int totalRecord = (int) (file.length()/SIZE);
System.out.print(totalRecord);
String gameName, publisher;
int year;
for(int loop=0; loop< totalRecord; loop++)
{
gameName = file.readUTF();
for(int innerloop=0; innerloop<20-gameName.length(); loop++ )
{
file.readByte();
}
publisher = file.readUTF();
for(int innerloop=0; innerloop<20-publisher.length(); loop++ )
{
file.readByte();
}
year = file.readInt();
wholeRecord += "|Game Name:" + gameName + " | Publisher: " + publisher + " | Year Published: " + year + "\n";
}
System.out.println( wholeRecord);
}
答案 0 :(得分:0)
for (int innerloop = 0; innerloop < 20 - gameName.length(); loop++)
问题出在这里。它应该是:
for (int innerloop = 0; innerloop < 20 - gameName.length(); innerloop++)
(两次)。
然而:
SIZE
是一个无效的假设。您不能假设字符串的writeUTF()
表示使用与字符串中的字符相同的字节数,再加上长度字的2。writeUTF()
和writeInt()
数据的文件不是文字,不应具有.txt
扩展名。