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
🌐
Programiz
programiz.com › java-programming › printwriter
Java PrintWriter (With Examples)
The printf() method can be used to print the formatted string. It includes 2 parameters: formatted string and arguments. For example, ... The formatted string includes both text and data. And, the arguments replace the data inside the formatted string. Hence the %d is replaced by 25. import ...
Discussions

file io - Is there a way to use Java PrintWriter to write to a specific line? - Stack Overflow
I have a Java program that uses PrintWriter to write text to a file using lots of .println() statements, everything works fine. What I want to know is: is there a way to write to a specific line in... 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
Common usage for File, Scanner, and PrintWriter classes
When it comes to Scanner you will probably never use that class ever again once you are out of the classroom. As far as File and PrintWriter those are used for file I/O which you will most certainly do. If you need to read or write to a file you will need to use the appropriate classes. Java I/O is easier to understand if you understand the Decorator design pattern as Decorator is used extensively in Java I/O. More on reddit.com
🌐 r/javahelp
10
4
April 14, 2022
import java.io.PrintWriter problem. No txt file appearing in folder.
It won't show up in the src folder, try checking in the project folder (with the classpath and project files). As people have likely suggested, you should be creating a File first, then wrapping the FileWriter in a BufferedWriter. Creating a File object isn't necessarily "required", but it is good practice to first ensure you can create the file to pinpoint any errors (among other functionality). The BufferedWriter part is simply for efficiency, and is only really required if you have a large amount of data to write. More on reddit.com
🌐 r/javahelp
12
1
February 3, 2017
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › io › PrintWriter.html
PrintWriter (Java Platform SE 8 )
1 month ago - Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will encode characters using the provided charset. ... fileName - The name of the file to use as the ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-io-printwriter-class-java-set-1
Java.io.PrintWriter class in Java | Set 1 - GeeksforGeeks
July 23, 2025 - Methods of PrinterWriter Class in Java are mentioned below: ... Syntax :public PrintWriter append(char c) Parameters: c - The 16-bit character to append Returns: This writer
🌐
Codecademy
codecademy.com › docs › java › printwriter
Java | PrintWriter | Codecademy
August 17, 2024 - Learn to code in Java — a robust ... Friendly.Beginner Friendly17 hours17 hours · PrintWriter writer = new PrintWriter(new File(file_name)); writer.println(text); writer.close();...
🌐
CodeGym
codegym.cc › java blog › java io & nio › java printwriter class
Java PrintWriter Class
January 9, 2025 - It is crucial to close the PrintWriter after completing file operations to: Free System Resources: Ensures that file descriptors and other resources are released. Flush Data: Guarantees that any buffered data is written to the file. Prevent Data Corruption: Minimizes the risk of incomplete writes or corrupted files. import java.io.File; import java.io.PrintWriter; public class EnsureCloseExample { public static void main(String[] args) { PrintWriter writer = null; try { // Create and initialize PrintWriter File file = new File("safeclose.txt"); writer = new PrintWriter(file); // Write data to the file writer.println("Always close resources properly."); } catch (Exception e) { System.out.println("An error occurred: " + e.getMessage()); } finally { // Ensure the PrintWriter is closed if (writer != null) { writer.close(); } } } }
Find elsewhere
🌐
Virginia Tech
courses.cs.vt.edu › ~cs1114 › JavaIOtutorial.html
Java I/o Tutorial
To make these tests fully automated, ... to read from a fixed input string as part of your test case. For output, create a PrintWriter that can write to a String object instead of the console....
🌐
Baeldung
baeldung.com › home › java › java io › printwriter vs. filewriter in java
PrintWriter vs. FileWriter in Java | Baeldung
December 1, 2023 - Learned the basic usage of FileWriter and PrintWriter with example code and understand their differences.
🌐
Oracle
docs.oracle.com › en › java › javase › 22 › docs › api › java.base › java › io › PrintWriter.html
PrintWriter (Java SE 22 & JDK 22)
July 16, 2024 - Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will encode characters using the provided charset. ... fileName - The name of the file to use as the ...
🌐
YouTube
m.youtube.com › watch
Java - I/O - PrintWriter
Share your videos with friends, family, and the world
Published   May 14, 2014
🌐
Coding Shuttle
codingshuttle.com › home › handbooks › java programming handbook › java printwriter class
Java PrintWriter Class | Coding Shuttle
April 9, 2025 - It supports writing text using methods like print(), println(), and printf(), much like how we use System.out, but it's important not to confuse PrintWriter with PrintStream (used by System.out).
🌐
Coderanch
coderanch.com › t › 408937 › java › Creating-file-PrintWriter
Creating a new file using PrintWriter. (Beginning Java forum at Coderanch)
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 ...
🌐
DZone
dzone.com › coding › java › java printwriter with example
Java PrintWriter With Example
February 19, 2020 - Basically, the above-mentioned methods use the platform's notion of a line separator, not a new-line character. One important thing about the PrintWriter class is that it never throws any I/O exceptions. However, its constructor does in case of an error. This class has a method checkError(), which can be invoked by the client to check whether any error is occurred. You may also like: Java 8 (A Comprehensive Look): Part 1.1 - Lambdas Under the Hood
🌐
O'Reilly
oreilly.com › library › view › java-for-dummies › 9781118239742 › a68_07_9781118239742-ch04.html
PrintWriter Class - Java For Dummies Quick Reference [Book]
June 5, 2012 - The PrintWriter class lets you write data to an output stream. Although you can connect a PrintWriter to any object that implements Writer, you’ll use it most often in conjunction with a BufferedWriter object. The PrintWriter class is one of many Java I/O classes that use streams.
Author   Doug Lowe
Published   2012
Pages   288
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.io.printwriter
PrintWriter Class (Java.IO) | Microsoft Learn
[<Android.Runtime.Register("java/io/PrintWriter", DoNotGenerateAcw=true)>] type PrintWriter = class inherit Writer ... Prints formatted representations of objects to a text-output stream.
🌐
YouTube
youtube.com › watch
Java Tutorial #85 - Java PrintWriter Class with Examples - YouTube
Java Tutorial #85 - Java PrintWriter Class with ExamplesIn this video by Programming for Beginners we will learn Java PrintWriter Class with Examples, using ...
Published   September 25, 2022
🌐
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.

🌐
Scaler
scaler.com › home › topics › java class printwriter
Java Class PrintWriter - Scaler Topics
December 19, 2022 - In the above code, we have used different PrintWriter methods to print different data types to the console. We can write formatted data to an underlying Writer using the Java PrintWriter class java.io.PrintWriter.
🌐
CodeAhoy
codeahoy.com › java › PrintWriter-JI_10
Java PrintWriter Explained with Examples (Java 9+) | CodeAhoy
October 26, 2016 - Once we have opened the file, we’ll use PrintWriter.print(...), and PrintWriter.println(...) methods to write different data types: int, String and boolean to the file. package com.codeahoy.ex; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Main { public static void main(String[] args) { try { PrintWriter printWriter = new PrintWriter("out_codeahoy.txt"); printWriter.print(123); printWriter.print(" This is a normal string "); printWriter.print(false); printWriter.close(); } catch (FileNotFoundException fnf) { fnf.printStackTrace(); } } }