The fact that PrintWriter's method is called append() doesn't mean that it changes mode of the file being opened.

You need to open file in append mode as well:

PrintWriter pw = new PrintWriter(new FileOutputStream(
    new File("persons.txt"), 
    true /* append = true */)); 

Also note that file will be written in system default encoding. It's not always desired and may cause interoperability problems, you may want to specify file encoding explicitly.

Answer from axtavt on Stack Overflow
🌐
Coderanch
coderanch.com › t › 637179 › java › Appending-Existing-File-Overwriting
Appending to an Existing File instead of Overwriting It [Solved] (I/O and Streams forum at Coderanch)
Yes, FileWriter has a constructor which you can pass a filename and a boolean value in as a second parameter. If you pass in 'true' it will append to an existing file. ... Kevin Simonson wrote:But when I call the constructor for {PrintWriter} up above, it overwrites whatever the original contents ...
Discussions

How do you append data to an existing text file using java.io.PrintWriter?
How do you append data to an existing text file using java.io.PrintWriter? More on transtutors.com
🌐 transtutors.com
2
March 1, 2022
[Java] Write to existing file without overwriting said text file

TBH, just open the file and handle the FileNotFoundException as file systems can and tend to be volatile meaning in between the test a filecan be created or be destroyed just after the test. However, the issue is FileWriter is creating the file so the else will almost always be true...

More on reddit.com
🌐 r/learnprogramming
4
2
February 20, 2017
Appending to a text file with FileWriter & bufferedWriter - Support - Kotlin Discussions
Hi All, In the following example using FileWriter, two lines are appended to a text file using both the .write() and .append() methods, when the context mode is set to APPEND (true)… File("test_file2.txt").bufferedWriter().use { out-> out.write(("Line 1\r\n")) out.write(("Line 2\r\n")) } ... More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
1
March 16, 2022
PrintWriter is clearing my data.txt file

Try using

FileWriter fileWriter = new FileWriter(fileName,true); //true here signifies append mode
outputFile = new PrintWriter (fileWriter);
More on reddit.com
🌐 r/javahelp
2
3
July 13, 2016
🌐
BeginnersBook
beginnersbook.com › 2014 › 01 › how-to-append-to-a-file-in-java
How to append to a file in java using BufferedWriter, PrintWriter
PrintWriter gives you more flexibility. Using this you can easily format the content which is to be appended to the File. import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; class AppendFileDemo2 { public static void main( String[] args ) { try{ File file =new File("C://myfile.txt"); if(!file.exists()){ file.createNewFile(); } FileWriter fw = new FileWriter(file,true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); //This will add a new line to the file content pw.println(""); /* Below three statements would add three * mentioned Strings to the file in new lines.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › io › PrintWriter.html
PrintWriter (Java Platform SE 8 )
April 21, 2026 - An invocation of this method of the form out.append(c) behaves in exactly the same way as the invocation ... Java™ Platform Standard Ed.
🌐
GeeksforGeeks
geeksforgeeks.org › java › printwriter-appendcharsequence-int-int-method-in-java-with-examples
PrintWriter append(CharSequence, int, int) method in Java with Examples - GeeksforGeeks
July 11, 2025 - // Java program to demonstrate // PrintWriter append(CharSequence, int, int) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintWriter instance PrintWriter writer = new PrintWriter(System.out); // Get the charSequence // to be written in the stream CharSequence charSequence = "GFG"; // Get the starting index int startingIndex = 2; // Get the length of char int endingIndex = 3; // Write the portion of the charSequence // to this writer using append() method // This will put the charSequence in the stream // till it is printed on the console writer.append(charSequence, startingIndex, endingIndex); writer.flush(); } catch (Exception e) { System.out.println(e); } } }
🌐
How to do in Java
howtodoinjava.com › home › i/o › appending to a file in java
Appending to a File in Java
April 22, 2022 - To append a string to an existing file, open the writer in append mode and pass the second argument as true. String textToAppend = "Happy Learning !!"; Strinng filePath = "c:/temp/samplefile.txt"; try(FileWriter fw = new FileWriter(filePath, ...
Find elsewhere
🌐
Android Developers
developer.android.com › api reference › printwriter
PrintWriter | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Tutorialspoint
tutorialspoint.com › java › io › printwriter_append.htm
Java.io.PrintWriter.append() Method
package com.tutorialspoint; import java.io.*; public class PrintWriterDemo { public static void main(String[] args) { try { // create a new stream at system PrintWriter pw = new PrintWriter(System.out); // append chars pw.append('H'); pw.append('e'); pw.append('l'); pw.append('l'); pw.append('o'); // flush the writer pw.flush(); } catch (Exception ex) { ex.printStackTrace(); } } }
🌐
Roy Tutorials
roytuts.com › home › java › write or append to a file using java
Write Or Append To A File Using Java - Roy Tutorials
November 9, 2023 - public class FileApp { public static void main(String[] args) throws IOException { writeAppendToFile(null); } public static void writeAppendToFile(final String fileName) throws IOException { String outFileName = null; if (fileName == null || fileName.trim().length() <= 0) { final Date date = new Date(); final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); outFileName = sdf.format(date) + ".txt"; } else { outFileName = fileName; } PrintWriter pw = null; final File file = new File(outFileName); if (file.exists() && !file.isDirectory()) { pw = new PrintWriter(new FileWriter(file, true
🌐
Baeldung
baeldung.com › home › java › java io › java – write to file
Java - Write to File | Baeldung
December 1, 2023 - @Test public void whenAppendStringUsingBufferedWritter_thenOldContentShouldExistToo() throws IOException { String str = "World"; BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true)); writer.append(' '); writer.append(str); writer.close(); } ... @Test public void givenWritingStringToFile_whenUsingPrintWriter_thenCorrect() throws IOException { FileWriter fileWriter = new FileWriter(fileName); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.print("Some String"); printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000); printWriter.close(); }
🌐
Reddit
reddit.com › r/learnprogramming › [java] write to existing file without overwriting said text file
r/learnprogramming on Reddit: [Java] Write to existing file without overwriting said text file
February 20, 2017 -

so this is a part of my project that I'm struggling with. I need to be able to search if a file exists, and if it does then I could append to it without erasing the content of the original file. and if the file does not exist to make a new one. However I'm running into a problem in which when I enter a directory and a file name of a file that doesn't exist, it says it exists, and creates the file and adds data to it regardless of the fact not existing before running the program. What am I doing wrong here. I'm somewhat new to file writing

package writeToFile;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;

public class writeTo {

	public static void main(String[] args) throws Exception{

		String fileDirectory;
		String fileName;

		System.out.println("Please enter the directory to create a new text file (Don't include file name or extension at the end i.e (C:\\Users\\JohnDoe\\Desktop)");
		Scanner keyboard = new Scanner(System.in);
		fileDirectory = keyboard.nextLine();
		System.out.println("Please choose a file name for your text file (Don't Include .txt or any extensions at the end)");
		fileName = keyboard.nextLine();

		File newFile = new File(fileDirectory + "\\" + fileName +".txt");
		FileWriter fileWrite = new FileWriter(newFile, true);
		BufferedWriter bufferedWrite = new BufferedWriter(fileWrite);
		PrintWriter write = new PrintWriter(bufferedWrite);

		if(newFile.exists() == false){
			newFile.createNewFile();
			write.print("hello new worlkd");
			System.out.println("File Created and written to sucessfully, Please check " + fileDirectory +" For the File " + fileName);

		}

		else{
			System.out.println("The File " + fileName +" Already Exists, populating existing file");
			write.print("hello old worlkd");
		}


		write.close();
		keyboard.close();

	}
}
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-append-to-file
Java append to file | DigitalOcean
August 3, 2022 - File file = new File("append.txt"); FileWriter fr = new FileWriter(file, true); BufferedWriter br = new BufferedWriter(fr); PrintWriter pr = new PrintWriter(br); pr.println("data"); pr.close(); br.close(); fr.close(); You should use FileOutputStream to append data to file when it’s raw data, binary data, images, videos etc. OutputStream os = new FileOutputStream(new File("append.txt"), true); os.write("data".getBytes(), 0, "data".length()); os.close(); Here is the final java append to file program showing all the different options we discussed above.
🌐
Sentry
sentry.io › sentry answers › java › how to create a file and write to it in java
How to create a file and write to it in Java | Sentry
May 15, 2023 - This enables append mode, so the file will not be overwritten. import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[]args) { String stringToWrite = "\nJava files are easy"; try { BufferedWriter writer = new BufferedWriter(new FileWriter("newfile.txt", true)); writer.write(stringToWrite); writer.close(); } catch (IOException ioe) { System.out.println("Couldn't write to file"); } } }
🌐
Kotlin Discussions
discuss.kotlinlang.org › support
Appending to a text file with FileWriter & bufferedWriter - Support - Kotlin Discussions
March 16, 2022 - Hi All, In the following example using FileWriter, two lines are appended to a text file using both the .write() and .append() methods, when the context mode is set to APPEND (true)… File("test_file2.txt").bufferedWriter().use { out-> out.write(("Line 1\r\n")) out.write(("Line 2\r\n")) } FileWriter( "test_file2.txt", true ).use { out -> out.write("Appended Line 3\r\n") // append works here out.append("Appended Line 4\r\n") // append works here too!
🌐
W3Schools
w3schools.com › java › java_files.asp
Java Files
Variables Print Variables Multiple Variables Identifiers Constants (Final) Real-Life Examples Code Challenge Java Data Types
🌐
CodeChef
codechef.com › learn › course › java-development › XWBZJU › problems › TWOLMM29
Appending Text/Lines to Files in Java in Java
Test your Learn Java knowledge with our Appending Text/Lines to Files in Java practice problem. Dive into the world of java-development challenges at CodeChef.
🌐
Oracle
docs.oracle.com › en › java › javase › 16 › docs › api › java.base › java › io › PrintWriter.html
PrintWriter (Java SE 16 & JDK 16)
January 6, 2022 - Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset. ... Appends the specified character to this writer.
🌐
Reddit
reddit.com › r/javahelp › printwriter is clearing my data.txt file
r/javahelp on Reddit: PrintWriter is clearing my data.txt file
July 13, 2016 -

So i have made a file and it reads it properly with what I have provided. But when I add in the PrintWriter code it deletes all text in the data.txt file. Here is what I have written down.

public class files
{
   public static void main () throws Exception
   {
      Scanner inputFile;
      File fileName;
      PrintWriter outputFile;
      fileName = new File ("data.txt");
      outputFile = new PrintWriter (fileName);
      inputFile = new Scanner (fileName);
                 
    
      while (inputFile .hasNext())
         {
           //code
         }
     }
}

I have yet to add in a try/catch but I don't think that is why it wont work. I also tried slightly rearranging the order but that didn't work.

edit: Solved using

        Scanner inputFile;
        File fileName;
        PrintWriter outputFile;
        fileName = new File ("data.txt");
        inputFile = new Scanner (fileName);
        
        FileWriter fileWriter = new FileWriter(fileName,true); //true here signifies append mode
        outputFile = new PrintWriter (fileWriter);
🌐
GeeksforGeeks
geeksforgeeks.org › java › printwriter-appendcharsequence-method-in-java-with-examples
PrintWriter append(CharSequence) method in Java with Examples - GeeksforGeeks
July 11, 2025 - // Java program to demonstrate ... PrintWriter writer = new PrintWriter(System.out); // Write the CharSequence 'GFG' // to this writer using append() method // This will put the charSequence in the stream // till it is ...