我有一個文本文件中存儲的用戶名密碼,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