1

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 ?

John
  • 117
  • 1
  • 2
  • 13
  • 1
    How are you opening the text file? Programs like Notepad don't always respect new lines. – azurefrog Mar 22 '16 at 20:55
  • I see that you've tagged `ioexception` for your question, but you don't mentioned getting one when you run your program. What exception are you getting? If none, you should remove the tag. – azurefrog Mar 22 '16 at 20:57
  • 2
    see: http://stackoverflow.com/questions/207947/how-do-i-get-a-platform-dependent-new-line-character – Meiko Rachimow Mar 22 '16 at 20:57

2 Answers2

1

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();
    }
jonhid
  • 2,075
  • 1
  • 11
  • 18
0

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
Denis
  • 1,219
  • 1
  • 10
  • 15