【发布时间】:2017-08-28 07:05:25
【问题描述】:
关注这个thread:
我有一个文本文件存储该用户的用户名密码和最佳分数。
尝试制作一个简单的问答游戏。我有一个注册面板,当用户注册时,我将数据存储在这个文件中,并为新用户设置他的最佳分数 0。
每一行的文本文件格式是
{用户名} {密码} {bestScore}
当用户的得分超过他的 bestScore 时,我会尝试用 bestScore 替换文本文件中的实际得分。
好吧,回到那个话题。我做了@meriton 发布的所有内容,但文本文件仍然没有改变。这是我的代码:
if (gameData.getBestScore() < gameData.getScore()) {
int oldBestScore = gameData.getBestScore();
String oldLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + oldBestScore;
gameData.setBestScore(gameData.getScore());
String newLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + gameData.getBestScore();
// TODO replace the points in the text file
//first method
/*try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Users\\Niki\\Desktop\\Java Projects\\QuizGame\\QuizGame\\usernames.txt"))))) {
String line = br.readLine();
while (line != null) {
if (line.contains(gameData.getCurrentUser())) {
String newLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + gameData.getBestScore();
line = line.replace(line, newLine);
break;
}
line = br.readLine();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//second method
Path path = Paths.get("C:\\Users\\Niki\\Desktop\\Java Projects\\QuizGame\\QuizGame\\usernames.txt");
Charset charset = StandardCharsets.UTF_8;
String content = null;
try {
content = new String(Files.readAllBytes(path), charset);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(content);
content = content.replaceAll(oldLine, newLine);
System.out.println(content);
gameOverPanel.gameOverLabel.setText("<html><h1>You didn't answer correctly!</h1><hr><h2>The correct answer is: " + gameData.getCurrentQuestion().getCorrectAnswer().getText() + "</h2><h3>Congratulations! New High Score: " + gameData.getBestScore() + "</h3></html>");
}
else {
gameOverPanel.gameOverLabel.setText("<html><h1>You didn't answer correctly!</h1><hr><h2>The correct answer is: " + gameData.getCurrentQuestion().getCorrectAnswer().getText() + "</h2><h3>Your score: " + gameData.getBestScore() + "</h3></html>");
}
}
如您所见,我在编辑内容之前println,之后到控制台,一切正常。旧内容被新内容替换,但文件不会被新内容更新。
我也尝试按照我的方式进行操作,您可以在 //first 方法注释下的代码中看到注释部分。那个方法还是不行。
【问题讨论】:
-
好吧,你没有写入文件,那么你为什么期望它改变呢?
标签: java