1

我不能在我的文本文件中使用这段代码换行,这有什么问题?

try{
    oprint=new FileWriter("HighScores.txt",true);
} catch (IOException e1) {
    System.out.println("error");
}  
try{
    String stampa= "Player:  "+name+"  --- time "+ this.getDurata()+" s \n";
    oprint.write(stampa);
    oprint.close();
}catch(Exception e){
    System.out.println("error");
}
4

3 回答 3

3

尝试使用这个:

public static String newline = System.getProperty("line.separator");

接着:

oprint.write("Player:  " + "x" + "  --- time " + "durata" + " s " + newline);

这更好,因为不同的操作系统有不同的写新行的方式。Linux 使用“\n”,Mac 使用“\r”,Windows 使用“\r\n”作为换行符。

于 2012-06-25T11:42:27.790 回答
0

您确定您的编辑器或查看器不希望在行尾有回车 (CR) 吗?

如果是这样,请尝试以下操作:

String stampa = "Player:  "+name+"  --- time "+ this.getDurata()+" s \r\n";

或者你可以使用String.format

String stampa = String.format("Player: %s  --- time %d s %n", name, this.getDurata());

格式文档

'n' 行分隔符 结果是特定于平台的行分隔符

于 2012-06-25T11:40:20.810 回答
0

尝试包装FileWriterPrintWriter使用它的println()方法。

PrintWriter oprint;
try{
    oprint=new PrintWriter(new FileWriter("HighScores.txt",true));
    String stampa= "Player:  "+name+"  --- time "+ this.getDurata()+" s";
    oprint.println(stampa);//<- print with new line sign
    oprint.close();
}catch(Exception e){
    System.out.println("error");
}
于 2012-06-25T11:49:08.000 回答