If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.

As you stated the error is that the file cannot be created. If you read the documentation of PrintWriter constructor you can see

FileNotFoundException - If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

You should try creating a path for the folder it contains before:

File file = new File("C:/Users/Me/Desktop/directory/file.txt");
file.getParentFile().mkdirs();

PrintWriter printWriter = new PrintWriter(file);
Answer from Jack on Stack Overflow
🌐
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(); }
Discussions

[Java]Writing to a large file, PrintWriter vs Files.write
PrintWriter uses a buffer. It doesn't hold the entire file in memory, but it will hold a little bit in memory and do larger writes rather than writing everything as it comes in. This technique is way better from a performance standpoint because writing to a file is very slow, especially if you're on a spinning disk hard drive- it's something like 1000x slower to write to a disk than to write to memory. More on reddit.com
🌐 r/learnprogramming
2
1
March 17, 2016
java - how to use printwriter to create and write to a file - Stack Overflow
I am trying to create a new file and print data to said file using the printwriter class. My code looks like this File Fileright = new File("C:\\GamesnewOrder.txt"); PrintWriter pw = new PrintW... More on stackoverflow.com
🌐 stackoverflow.com
java - PrintWriter add text to file - Stack Overflow
In my online computer science class I have to write a program to determine the surface gravity on each planet in the solar system. I have gotten almost every aspect of it to work save one. I need to More on stackoverflow.com
🌐 stackoverflow.com
Cannot overwrite a txt file, can only append to it
My first suggestion would be to double and triple check that you're actually writing to the file that you think you are. For example, use File objects instead of just the file name in the FileWriter constructor. Use File.getAbsolutePath() and check that is the file that you think it is. Using a relative file path can often lead to mistakes like this, where you're looking for files in the wrong directory. If you suspect that file is being held open somewhere (which i'm skeptical of--I think you'd be getting exceptions in that case), you can try using OS-specific utilities to look at the file handles. For example, on Windows 7 and newer, you can use the Resource Monitor to search for file handles (in the "CPU" tab). More on reddit.com
🌐 r/javahelp
5
0
April 29, 2022
🌐
Coderanch
coderanch.com › t › 408937 › java › Creating-file-PrintWriter
Creating a new file using PrintWriter. (Beginning Java forum at Coderanch)
December 12, 2007 - If you want to add to the file instead of overwriting its contents, you need to use FileWriter directly, as that has the possibility to specify whether to overwrite or append: Don't be worried about using a FileWriter - this is exactly what PrintWriter uses when created using a String or File.
🌐
Programiz
programiz.com › java-programming › printwriter
Java PrintWriter (With Examples)
In order to create a print writer, we must import the java.io.PrintWriter package first. Once we import the package here is how we can create the print writer. ... // Creates a FileWriter FileWriter file = new FileWriter("output.txt"); // Creates a PrintWriter PrintWriter output = new ...
🌐
Codecademy
codecademy.com › docs › java › printwriter
Java | PrintWriter | Codecademy
August 17, 2024 - It is a part of the java.io package and provides convenient methods for writing different types of data (like strings, numbers, or objects) to a file or another output stream in a human-readable, formatted way.
🌐
Baeldung
baeldung.com › home › java › java io › printwriter vs. filewriter in java
PrintWriter vs. FileWriter in Java | Baeldung
December 1, 2023 - It provides a convenient method to write characters to a file using a preset buffer size. FileWriter doesn’t flush the buffer automatically. We need to invoke the flush() method. However, when FileWriter is used with the try-with-resources block, it automatically flushes and closes the stream when exiting the block. Furthermore, it throws an IOException in the case of a missing file, when a file cannot be opened, etc. Unlike PrintWriter, it can’t write formatted text to a file.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › io › PrintWriter.html
PrintWriter (Java Platform SE 7 )
Creates a new PrintWriter, without automatic line flushing, with the specified file and charset. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will encode characters using the provided charset. ... file - The file to use as the destination of this writer.
Find elsewhere
🌐
CodeGym
codegym.cc › java blog › java io & nio › java printwriter class
Java PrintWriter Class
January 9, 2025 - Here is the PrintWriter object to write text in the file. PrintWriter fileOutput = new PrintWriter("FileOutput.txt"); This constructor takes a String input as the file name. Creates a file of the specified name and writes the text data in it.
🌐
Reddit
reddit.com › r/learnprogramming › [java]writing to a large file, printwriter vs files.write
r/learnprogramming on Reddit: [Java]Writing to a large file, PrintWriter vs Files.write
March 17, 2016 -

So, I'm reading from a db, and then writing to a file.

We have a large amount of records, so the file will become rather large. like 700mb - 1gb. Or more.

Right now I'm only playing with 1k records.

try(PrintWriter assetfilewriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath1, false)))) {
	for(int iter=0; iter<RSsize; iter++){
		//do logic, get fields, save it to a string called logtxt
	//Using Files.write
		Files.write(Paths.get(filePath2), logtxt.getBytes(), StandardOpenOption.WRITE);
	//Using PrintWriter
		assetfilewriter.print(logtxt);
	}
}

Now when I sit and look at the output folder, the process takes around 10-20 seconds so I can see the files being updated.

filepath2, which is the Files.Write method, is constantly being updated.

filepath1, which is the PrintWriter method, remainds at 0kb untill apparently the loop finishes, then it writes to the file in one shot.

Which is the better method? Since we have a large amount of records, I don't really want java to store everything in memory and write it all at once. I've run into java memory exceptions a few times already.

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › io › PrintWriter.html
PrintWriter (Java Platform SE 8 )
March 16, 2026 - Creates a new PrintWriter, without automatic line flushing, with the specified file name. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will encode characters using the default charset for this instance of the Java virtual machine.
🌐
Javatpoint
javatpoint.com › java-printwriter-class
Java PrintWriter Class
June 28, 2013 - Fields Modifier Type Field Description ... Object Methods Modifier and Type Method Description void close() It... ... Java - This class is used for reading and writing to random access file....
🌐
Medium
medium.com › geekculture › using-printwriter-vs-filewriter-in-java-2958df85f105
Using PrintWriter vs FileWriter in Java | by Anna Scott | Geek Culture | Medium
August 19, 2021 - public static void main(String[] args) { //creating object of class File using path - is not the same as //creating file File filePrintWriter = new File("printwriter.txt"); File fileFileWriter = new File("filewriter.txt"); try { //creating object of PrintWriter class with File object as //parameter PrintWriter printWriter = new PrintWriter(filePrintWriter); //using methods and close write inherrited from parent //Writer printWriter.write("I love Java"); /*Closes the stream and releases any system resources associated with it. It needs to be done to flush buffer*/ printWriter.close(); //creatin
🌐
How to do in Java
howtodoinjava.com › home › i/o › java write to file: clean code vs. performance
Java Write to File: Clean Code vs. Performance
October 12, 2023 - Path filePath = Path.of("demo.txt"); ... printWriter.printf("Blog name is %s", "howtodoinjava.com"); } Use FileOutputStream to write binary data to a file....
🌐
Oracle
docs.oracle.com › en › java › javase › 26 › docs › api › java.base › java › io › PrintWriter.html
PrintWriter (Java SE 26 & JDK 26)
March 16, 2026 - Creates a new PrintWriter, without automatic line flushing, with the specified file and charset. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will encode characters using the provided charset. ... file - The file to use as the destination of this writer.
🌐
DZone
dzone.com › coding › java › java printwriter with example
Java PrintWriter With Example
February 19, 2020 - The PrintWriter class implements all the methods of the PrintStream class. However, this class does not have any methods that are used for writing raw bytes. Note: the PrintWriter class is also used for write a file in Java.
🌐
CodeAhoy
codeahoy.com › java › PrintWriter-JI_10
Java PrintWriter Explained with Examples (Java 9+) | CodeAhoy
October 26, 2016 - PrintWriter​(File file, String csn): Creates a new PrintWriter, without automatic line flushing, with the specified file and charset. PrintWriter​(OutputStream out): Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream. PrintWriter​(OutputStream out, boolean autoFlush): Creates a new PrintWriter from an existing OutputStream. PrintWriter​(Writer out): Creates a new PrintWriter, without automatic line flushing.
🌐
BeginwithJava
beginwithjava.com › home › coding › writing data to a text file in java
Writing data to a text file in Java - BeginwithJava
October 7, 2024 - Writing Data to a Text File The simplest way to write text to a file requires us to use PrintWriter class from the standard package java.io . The class PrintWriter has the familiar print() and println() methods we have been using for writing to the console. The following program writes the ...
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › io › PrintWriter.html
PrintWriter (Java SE 17 & JDK 17)
January 20, 2026 - Creates a new PrintWriter, without automatic line flushing, with the specified file name. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will encode characters using the default charset for this instance of the Java virtual machine.