java - 我无法在文件的新行中写入数据

标签 java file line newline printwriter

无论我做了什么,我都没有在文件的新行上写入新数据。 我该如何修复它?

例如 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/

相关文章:

html - 应用填充时,内联 block 元素下降到第二行

java - 如何从输入的文本文件中删除整行

android - 简单的 HttpURLConnection POST 文件 multipart/form-data 从 android 到 google blobstore

java - Java中的动态对象注册

java - 检查设备是否接受证书

C# GemBox Excel 导入错误

javascript - Highstock - 禁用垂直指示器

powershell - powershell删除行的第一个字符

java - 与功能文件不同的模块中的 CUCUMBER 功能定义

java - Maven 依赖冲突 : org. w3c.dom.ElementTraversal