0

How to append text to an existing file in Java?

I am using the method mentioned in the solution and i am taking user input. But the text is appending with the last word. is there any way to add an new line there?

  Scanner sc= new Scanner(System.in); 
        System.out.print("Enter a string: ");  
        String str= sc.nextLine(); 
        try {
            Files.write(Paths.get("C:\\Users\\souravpal\\Documents\\Bandicam\\buddy.txt"), str.getBytes(), StandardOpenOption.APPEND);
        }catch (IOException e) {
            //exception handling left as an exercise for the reader
        }

2 Answers2

0

You must use the new line character \n in your str variable if you want to move to the next line.

String str = "\n" + sc.nextLine();

You also should put it before the input becouse you will append it at the end of the file.

evgzabozhan
  • 140
  • 1
  • 11
0

use the System.lineSeparator() constant that applies at runtime and compatible with all OS.

Files.write(Paths.get("C:\\Users\\souravpal\\Documents\\Bandicam\\buddy.txt"),
                    (System.lineSeparator() + str).getBytes(),StandardOpenOption.APPEND);