简体   繁体   中英

How to make new lines in Buffer Writer - Java

I am trying to make my statement appear in new lines when I open up the text file, I used the "\\n" but no luck. My code is below:

    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();
    }

Right now it just appears in a long line, how can I make the information appear in in new a line ?

With String.format( ) you can use %n as platform agnostic sign for carriage return, %d is for ints and %s for Strings. The message inside "... " gets filled with the values provided in same order after.

    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();
    }

Your code works fine. you need to use "\\n" at the start of your write function if you want to start that line from new line. try this modified code may be it will make things clear for you:

 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();
}

I got this output for this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM