我有一个文本文件中存储的用户名密码,bestscore该用户。
试图做一个简单的问答游戏。我有一个注册面板,当用户注册时,我将数据存储在此文件中,并为新用户创建最佳分数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
编辑内容之前和之后的控制台和一切正常存在。旧内容将替换为新内容,但文件不会更新为新内容。
此外,我试图按照我的方式做到这一点,你可以在我的代码// //第一个方法评论下看到注释部分。这种方式仍然没有奏效。
那么,你没有写入文件,那么你为什么会期望它改变? – Mena
http://stackoverflow.com/questions/23466179/java-replace-specific-string-in-textfile – freedev
可能重复[java替换文本文件中的特定字符串](http://stackoverflow.com/questions/ 23466179/java-replace-specific-string-in-textfile) – freedev