【问题标题】:I can't write data on a new line in a file我无法在文件的新行上写入数据
【发布时间】: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


【解决方案1】:

代码很狡猾,但实际上应该符合您的期望。

您可能正在使用 Windows 记事本应用程序查看生成的文件。它期望 "\r\n" 作为换行符分隔符,与大多数其他 Windows 应用程序一样。

【讨论】:

  • 不,我正在使用 JCreator 查看生成的文件。
  • 这仍然可能是原因 =) 尝试将 txt 输出到 System.out 以查看换行符是否已实际写入以及是否已写入。尝试将行分隔符更改为\r\n
【解决方案2】:

使用以下代码

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 + name + " " + score;
        pw = new PrintWriter(Checker);// writing the checker

        pw.println(txt);
    } catch (FileNotFoundException fnfe) {

        fnfe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        sc.close();
        pw.close();
    }
}

}

【讨论】:

  • exists()/createNewFile() 部分是毫无意义的,像往常一样,仅仅代码不是这里的答案。你得解释一下,
猜你喜欢
  • 2011-12-17
  • 1970-01-01
  • 2017-06-27
  • 2012-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
相关资源
最近更新 更多