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

Java在文件中写入和读取字节,java,save,byte,fileinputstream,fileoutputstream,Java,Save,Byte,Fileinputstream,Fileoutputstream,在我正在编写的程序中,我将某些值作为字节保存到一个文件中,我希望加载该文件并读取每个字节dis.read()但每次我这样做时,值都不正确。这是我的保存代码: file2 = new File(newComputer.file1.toString() + "\\saves\\" + name); try { FileOutputStream fos = new FileOutputStream(file2 + ".dat"); DataOutputStream dos = new

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

然而,
readInt()
方法从文件中读取一个完整的32位(48位字节),这就是您正在写入文件的内容。

什么是
dis.read()
do?@SotiriosDelimanolis我很确定它会读取文件的下一个字节?但那只是我,我在字节方面不是很好。javadoc。是的,它确实读取下一个字节。您正在为
x
位置写入
int
,但只读取
字节。你看到了吗?这些是不等价的?谢谢!解决了我的问题@索蒂里奥斯德里曼努利斯酒店