在我正在编写的程序中,我将某些值作为字节保存到文件中,我想加载该文件并读取每个字节dis.read();
,但每次执行此操作时,值都会出错。这是我的保存代码:
file2 = new File(newComputer.file1.toString() + "\\saves\\" + name);
try {
FileOutputStream fos = new FileOutputStream(file2 + ".dat");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(character.pos.x);
dos.writeInt(character.pos.y);
dos.writeInt((int)Minecraft.sx);
dos.writeInt((int)Minecraft.sy);
dos.writeInt((int)Minecraft.dir);
dos.flush();
dos.writeInt(sky.r);
dos.writeInt(sky.g);
dos.writeInt(sky.b);
dos.writeInt(sky.dayFrame);
dos.writeInt(sky.changeFrame);
dos.writeInt(sky.time);
dos.flush();
dos.close();
} catch(Exception e) {
e.printStackTrace();
}
这是加载代码:
file2 = new File(newComputer.file1.toString() + "\\saves\\" + name);
try {
FileInputStream fis = new FileInputStream(file2);
DataInputStream dis = new DataInputStream(fis);
int tmp = 0;
//first get the character's x position
tmp = dis.read();
System.out.println("x: " + tmp);
character.x = tmp;
//then get the character's y position
tmp = dis.read();
System.out.println("y: " + tmp);
character.y = tmp;
//then get the camera's x position
tmp = dis.read();
System.out.println("sx: " + tmp);
Minecraft.sx = tmp;
//then get the camera's y position
tmp = dis.read();
System.out.println("sy: " + tmp);
Minecraft.sy = tmp;
//then get the character's facing position
tmp = dis.read();
System.out.println("facing: " + tmp);
Minecraft.dir = tmp;
//then get the sky's RGB colors
tmp = dis.read();
System.out.println("r: " + tmp);
sky.r = tmp;
tmp = dis.read();
System.out.println("g: " + tmp);
sky.g = tmp;
tmp = dis.read();
System.out.println("b: " + tmp);
sky.b = tmp;
//render the world
Minecraft.hasStarted = true;
Minecraft.played++;
} catch (Exception ex) {
ex.printStackTrace();
}
答案 0 :(得分:1)
那是因为您正在使用read()
代替readInt()
使用read()
返回int
,其中最低8位是从文件读取的单字节。
但是,readInt()
方法从文件中读取完整的32位(4个8位字节),这就是您要写入文件的内容。