-3

我制作了自己的缓冲写入器,它可以工作。但不知道是不是真的?

当我注销时我做了一个缓冲阅读器(200 个硬币),当我登录时我得到(545453 个硬币)或其他数量,我确定它是缓冲写入器,请帮助!

public static int coins;
private static final String DIR = "./Data/";
    public static boolean SavePlayer;

    public static void saveAll() {
        SavePlayer = true;
        if (!SavePlayer) {
            System.out.println("[WoG Error]: Their was an error saving players.");
            return;
        }
        saveGame();
    }

    public static boolean saveGame() {
        if (Player.playerName == null) {
            return false;
        }
        try {
            File file = new File(DIR + Player.playerName.toLowerCase() + ".dat");
            if (!file.exists()) 
                file.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            DataOutputStream o = new DataOutputStream(fileOutputStream);
            o.writeUTF(Player.playerName);
            o.writeInt(Player.coins);
            //o.writeInt(Player.height);
            o.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean loadGame() throws InterruptedException {
        try {
            File file = new File(DIR + Player.playerName.toLowerCase() + ".dat");
            if (!file.exists()) {
                System.out.println("[WoG Error] Sorry but the account does not exist.");
                return false;
            }
            FileInputStream fileInputStream = new FileInputStream(file);
            DataInputStream l = new DataInputStream(fileInputStream);
            Player.playerName = l.toString();
            Player.coins = l.readInt();
            //Player.height = l.readInt();
            l.close();
            fileInputStream.close();
            Player.home();
        } catch (final IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}

如何让它正确保存所有(整数)?

4

3 回答 3

5

从这 3 行来看,您似乎在保存玩家的姓名,然后进行硬币计数......

DataOutputStream o = new DataOutputStream(fileOutputStream);
o.writeUTF(Player.playerName); 
o.writeInt(Player.coins);

然后尝试像这样再次读回它们:

DataInputStream l = new DataInputStream(fileInputStream);
Player.playerName = l.toString(); // <-- change to l.readUTF()
Player.coins = l.readInt();

我注意到您正在使用l.toString()而不是l.readUTF().

你确定需要用对应的方法读回保存的数据吗?

换句话说,如果您使用 保存数据,则o.writeUTF()需要使用 读回数据l.readUTF()

喜欢就喜欢。

于 2013-08-30T20:01:01.233 回答
2

改变

Player.playerName = l.toString();

Player.playerName = l.readUTF();

通常,您应该使用诸如PrintWriter写入文件之类的东西。您不必编写像writeUTFor之类的低级操作writeInt。你可以直接做

printWriter.println(playerName);

在阅读时,使用ScannerBufferedReader

于 2013-08-30T20:02:44.270 回答
2

这是错误的:

Player.playerName = l.toString();

您没有从DataInputStream此处读取任何数据,您只是将DataInputStream对象转换为字符串。调用readUTF()而不是toString()

Player.playerName = l.readUTF();
于 2013-08-30T20:02:46.803 回答