如何在Buffer Writer中创建新行 - Java

时间:2016-03-22 20:53:07

标签: java

当我打开文本文件时,我试图让我的语句出现在新行中,我使用了“\ n”但没有运气。我的代码如下:

    try {

        FileWriter ac = new FileWriter("D:\\programming\\Java\\JavaBanking\\Transactions.txt",true);
        BufferedWriter fw = new BufferedWriter(ac);

        fw.write("You have chosen the following amount:" + String.valueOf(amount)+ "\n" +  " the number:" + getNumber() + "Is the chosen number"

              );
        fw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

现在它只是出现在一条长行中,如何让信息以新的一行显示?

2 个答案:

答案 0 :(得分:1)

使用String.format(),您可以使用%n作为回车的平台无关标志,  %d用于整数和 字符串的%s。 “...”内的消息将填充在之后以相同顺序提供的值。

    try {

        FileWriter ac = new FileWriter("D:\\programming\\Java\\JavaBanking\\Transactions.txt",true);
        BufferedWriter fw = new BufferedWriter(ac);

        String message = String.format(
                "You have chosen the following amount: %d %n the number: %d Is the chosen number",
                 amount, 
                 getNumber());

        fw.write(message);

        fw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

答案 1 :(得分:0)

您的代码运行正常。你需要使用" \ n"如果要从新行开始该行,则在写入函数开始时。尝试这个修改过的代码可能会让你明白:

 try {

    FileWriter ac = new FileWriter("Transactions.txt",true);
    BufferedWriter fw = new BufferedWriter(ac);
    fw.write("\nThis is new line");
    fw.write("\nYou have chosen the following amount:" + String.valueOf("23")+ "\n" +  " the number:"+"Is the chosen number" );
    fw.close();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

我为此代码获得了此输出:

This is new line
You have chosen the following amount:23
  the number:Is the chosen number