gpt4 book ai didi

Java 向文件写入字节和从文件读取字节

转载 作者:太空宇宙 更新时间:2023-11-04 06:53:37 25 4
gpt4 key购买 nike

在我正在编写的程序中,我将某些值作为字节保存到文件中,并且我想加载该文件并读取每个字节 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();
}

最佳答案

那是因为您使用的是 read() 而不是 readInt()

使用read()返回一个int,其中最低8位是从文件读取的单个字节。然而,readInt() 方法从文件中读取完整的 32 位(4 个 8 位字节),这就是您要写入文件的内容。

关于Java 向文件写入字节和从文件读取字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23038554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com