无论我做了什么,我都没有在文件的新行上写入新数据。 我该如何修复它?
例如 Mary 的分数是 100,smith 的分数是 150,但在 txt 文件中是
mary 100smith 150
我想在新行中添加smith 150
public class HighScores {
public HighScores(){
String txt = "";
Scanner sc = null;
PrintWriter pw = null;
File Checker = null;
try{
Checker = new File("highScores.txt");
if(!Checker.exists()){
Checker.createNewFile();
}
sc = new Scanner(new File("highScores.txt"));
while(sc.hasNextLine()){
txt = txt.concat(sc.nextLine()+"\n");
}
String score=String.valueOf(Game3.score);
String name = NewPlayer.name;
txt = txt.concat(name + " "+ score +"\n");
pw = new PrintWriter(Checker);// writing the checker
pw.write(txt +"\r\n");
pw.println() 也给出了同样的问题。
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
sc.close();
pw.close();
}
}
}
最佳答案
该代码很危险,但实际上应该按照您的期望进行操作。
您可能正在使用 Windows 记事本应用程序查看生成的文件。它需要 "\r\n"
作为换行符分隔符,就像大多数其他 Windows 应用程序一样。
关于java - 我无法在文件的新行中写入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36513915/