【发布时间】:2016-04-09 07:19:57
【问题描述】:
无论我做什么,我都没有在文件的新行上写入新数据。 我该如何解决?
例如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();
}
}
}
【问题讨论】:
-
不要使用 concat() 和硬编码
\n或\r\n。打开您的 PrintWriter,然后使用 println() 写入一些文本,然后是 EOL,或使用 print() 写入一些文本,而不是 EOL。并尊重 Java 命名约定:变量以小写字母开头。 -
我使用了println,但第二个数据又不在新行中
-
没有办法在不到 1 分钟的时间内更改所有代码并编写此新注释。再次阅读我的评论。
-
看这个帖子,让事情变得简单,它会更容易和持久,如何用Java stackoverflow.com/questions/19084352/…将换行符写入文件
-
println()not 是否会出现同样的问题。它提供了解决方案。
标签: java file line newline printwriter