我的项目中有一个txt文件“ HighScoreList.txt”。 问题是该文件上必须有字符,但是当我在Eclipse中打开它时,它是空的。将其从eclipse中删除,并用记事本打开它会从该文件中删除所有字符。 我的方法写在那个文件上。
public void registerHighScore(Player p) {
int score = p.getScore();
String name = p.getName();
{
currentHighScores.add("X. "+name+" - "+score); //place doesnt matter as the actual place gets determined in formatHList
formatHList();
}
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter(HighScoreManager.class.getResource("/highscore/HighScoreList.txt").getPath()));//persistancy
for (String s : currentHighScores) {
writer.write(s);
writer.newLine();
writer.flush();
}
writer.close();
} catch (IOException e) {
return;
}
}
我检查了文本文件中是否必须包含字符,因为
public ArrayList<String> getCurrentHighScores() {
ArrayList<String> result = new ArrayList<String>();
try {
BufferedReader bufferedReader = new BufferedReader(
new FileReader(HighScoreManager.class.getResource("/highscore/HighScoreList.txt").getPath()));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.add(line);
}
bufferedReader.close();
return result;
} catch (IOException e) {
}
return null;
}
使用该方法创建的ArrayList实际上包含X.Name-Score格式的字符串。