Java在文件中写入和读取字节



在我正在制作的程序中,我将某些值作为字节保存到文件中,我想加载该文件并读取每个字节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位字节),这就是您要写入文件的内容。

相关内容

  • 没有找到相关文章

最新更新