1

This is code that deletes the content of the file then writes on it I want to write in the file without deleting the content and write on the last line

import java.io.*;
import java.util.Scanner;

public class SetValues {

    public void setNumberPhone(String numberPhone) throws UnsupportedEncodingException {
        Scanner input = new Scanner(System.in);
        PrintWriter pr = null;

        try {
            input = new Scanner("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt");
            pr = new PrintWriter("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt", "UTF-8");

        } catch (FileNotFoundException e) {
            System.out.println("Not Open" + e.getMessage());
            System.exit(0);
        }

        if (input.hasNext()) {
            pr.println(numberPhone);
        }
        pr.close();

    }
}
ric
  • 627
  • 1
  • 12
  • 23
  • how about using file output stream ? – Lokesh Pandey Dec 16 '17 at 10:30
  • 1
    Read this - https://stackoverflow.com/questions/13741751/modify-the-content-of-a-file-using-java – ric Dec 16 '17 at 10:30
  • If you are using Java 7 or later, you can use https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-. The option to append being `StandardOption.APPEND` – Veera Dec 16 '17 at 10:38

1 Answers1

1
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.*;

OutputStream os = Files.newOutputStream(Paths.get("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt"), APPEND);
PrintWriter pr = new PrintWriter(os);

pr.println("TEXT");

This will create an output stream wherein any output text will be appended to the current contents of the file. You can use the OutputStream to create a PrintWriter. More information can be found at the Java documentation

Zachary
  • 1,693
  • 1
  • 9
  • 13