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
🌐
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.
Discussions

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]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 - Writing to a file with printwriter - Stack Overflow
Hi I'm a beginner to file I/O and I'm having a small problem with writing to a file. What my program should do is write a username and password to a file. Here's my code (ill describe my problem af... 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
🌐
Coderanch
coderanch.com › t › 408937 › java › Creating-file-PrintWriter
Creating a new file using PrintWriter. (Beginning Java forum at Coderanch)
December 12, 2007 - In other words, move the following three lines above the "while" loop: File file = new File("output.txt"); FileWriter writer = new FileWriter(file, true); PrintWriter output = new PrintWriter(writer); And move this one outside the closing brace of the while loop: output.close(); Just leave ...
🌐
CodeGym
codegym.cc › java blog › java io & nio › java printwriter class
Java PrintWriter Class
January 9, 2025 - Output: Creates a new file named newfile.txt if it does not already exist and writes the specified data to it. It is crucial to close the PrintWriter after completing file operations to:
🌐
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
🌐
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 ...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › io › PrintWriter.html
PrintWriter (Java Platform SE 8 )
3 days ago - 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.
🌐
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.
🌐
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 - Using PrintWriter vs FileWriter in Java PrintWriter and FileWriter are JAVA classes that allow writing data into files. public static void main(String[] args) { //creating object of class File …
🌐
QBasic on Your Computer
chortle.ccsu.edu › java5 › Notes › chap23 › ch23_12.html
PrintWriter
Above is a program that creates the file myOutput.txt and writes several lines of characters to that file. The constructor creates an object for the file and also creates a disk file: PrintWriter output = new PrintWriter( "myOutput.txt" );
🌐
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]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.

🌐
Stack Overflow
stackoverflow.com › questions › 50111096 › writing-to-a-file-with-printwriter
java - Writing to a file with printwriter - Stack Overflow
This simple constructor indicates that you want to write to the file in append mode. ... private static void Register() throws FileNotFoundException{ try{ FileWriter fw = new FileWriter("info.txt", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw); Scanner scan = new Scanner(System.in); System.out.println("Enter a username: "); String username = scan.nextLine(); System.out.println("Enter a password: "); String password = scan.nextLine(); out.println(username + " " + password); out.flush(); }catch(IOException e){ e.printStackTrace(); } }
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › io › printwriter
Java PrintWriter Example - Java Code Geeks
July 17, 2020 - PrintWriter uses an instance of BufferedWriter to write to the final destination. Here, the file handle is passed to the FileOutputstream class to write to the destination. Data is stored in a buffer before writing to optimize the I/O.
🌐
Processing
processing.org › reference › printwriter
PrintWriter / Reference / Processing.org
For the file to be made correctly, it should be flushed and must be closed with its flush() and close() methods (see above example). Copy · PrintWriter output; void setup() { // Create a new file in the sketch directory output = createWriter("positions.txt"); } void draw() { point(mouseX, mouseY); output.println(mouseX); // Write the coordinate to the file } void keyPressed() { output.flush(); // Writes the remaining data to the file output.close(); // Finishes the file exit(); // Stops the program } print()Adds data to the stream ·
🌐
Iastate
web.cs.iastate.edu › ~smkautz › cs227s16 › labs › lab8 › page06.html
Writing to a file
This program will read from System.in and write whatever you type to a file called mydocument.txt: import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class TextEditor { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(System.in); File outFile = new File("mydocument.txt"); PrintWriter out = new PrintWriter(outFile); // Echo keyboard input out to the file.
🌐
Team Treehouse
teamtreehouse.com › community › printwriter-vs-filewriter
PrintWriter vs. FileWriter (Example) | Treehouse Community
July 7, 2016 - I'll take a wild guess and say PrintWriter is good for txt files with Strings in them, while FileWriter is for java and other types of files. hope I've helped. ... FileWriter's write() method that accepts a String only writes a portion of a String to a file.