我制作了自己的bufferedwriter,它很有效。但我不知道是不是真的?
我做了一个小丑恐惧器,当我注销时,我有(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;
}
}
如何使其正确保存所有(整数)?
从这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()
读回数据。
喜欢对喜欢。
更改
Player.playerName = l.toString();
至
Player.playerName = l.readUTF();
通常,您应该使用类似PrintWriter
的东西来编写文件。您不必编写像writeUTF
或writeInt
这样的低级别操作。你可以直接做
printWriter.println(playerName);
阅读时,使用Scanner
或BufferedReader
这是错误的:
Player.playerName = l.toString();
这里没有从DataInputStream
读取任何数据,只是将DataInputStream
对象转换为字符串。调用readUTF()
而不是toString()
:
Player.playerName = l.readUTF();