1
在我正在做的一個程序中,我將某些值保存爲字節到一個文件,我想加載該文件並讀取每個字節dis.read();
但每次我這樣做,值出現不正確。這是我保存代碼:Java寫入和從文件讀取字節
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();
}
'dis.read();'做了什麼? –
@SotiriosDelimanolis我很確定它讀取文件的下一個字節?但是,就我而言,就字節而言,我不是很好。 –
[Here's](http://docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.html)javadoc。是的,它讀取下一個字節。您正在爲'x'位置寫入'int',但只讀取'byte'。你看到這些是不是等同的? –