Introduction
Writing data to files is one of the most common operations in Java programming. Whether you are saving user information, generating reports, writing application logs, exporting CSV files, creating configuration files, or storing program output, Java provides several powerful classes and APIs for writing data to files.
Java supports multiple approaches for file writing through the java.io and java.nio.file packages. Depending on your application’s requirements, you can write data character by character, line by line, or write an entire string or byte array at once.
Some of the most commonly used classes for writing files include:
- FileWriter
- BufferedWriter
- PrintWriter
- FileOutputStream
- Files
Why Write Files?
Writing files is essential in many real-world applications.
Common use cases include:
- Saving user registration data
- Creating log files
- Exporting reports
- Generating invoices
- Writing configuration files
- Saving application settings
- Creating CSV files
- Storing program output
- Generating backup files
Without file writing, applications would not be able to save data permanently.
Method 1: Writing a File Using FileWriter
FileWriter is one of the simplest classes for writing text files.
Example
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("students.txt");
writer.write("Rahul\n");
writer.write("Amit\n");
writer.write("Priya\n");
writer.close();
System.out.println("File written successfully.");
} catch(IOException e) {
e.printStackTrace();
}
}
}
Output
The file students.txt will contain:
Rahul
Amit
Priya
Method 2: Appending Data Using FileWriter
By default, FileWriter overwrites the existing file.
To append data instead, use the second constructor parameter.
FileWriter writer = new FileWriter("students.txt", true);
writer.write("Neha\n");
writer.close();
Now the new data is added to the end of the file instead of replacing its contents.
Method 3: Writing a File Using BufferedWriter
BufferedWriter improves performance by writing data through an internal buffer.
Example
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
BufferedWriter writer =
new BufferedWriter(new FileWriter("students.txt"));
writer.write("Rahul");
writer.newLine();
writer.write("Amit");
writer.newLine();
writer.write("Priya");
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Advantages
- Faster than FileWriter
- Efficient for large files
- Supports newLine()
Method 4: Writing a File Using PrintWriter
PrintWriter is useful for writing formatted text.
Example
import java.io.PrintWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
PrintWriter writer =
new PrintWriter("students.txt");
writer.println("Rahul");
writer.println("Amit");
writer.println("Priya");
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
println() automatically inserts a new line after each statement.
Method 5: Writing a File Using Files.write()
The Files class is part of the java.nio.file package.
Example
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
List students = List.of(
"Rahul",
"Amit",
"Priya"
);
Files.write(Paths.get("students.txt"), students);
}
}
This method writes all lines to the file in a single statement.
Method 6: Writing a String Using Files.writeString() (Java 11)
Java 11 introduced writeString().
Example
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Files.writeString(
Paths.get("message.txt"),
"Welcome to Java File Handling!"
);
}
}
This method is simple and concise for writing a complete string.
Method 7: Writing Binary Files Using FileOutputStream
FileOutputStream is used for binary data such as images, PDFs, and audio files.
Example
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileOutputStream output =
new FileOutputStream("numbers.bin");
output.write(65);
output.write(66);
output.write(67);
output.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
The values are written as bytes.
Comparison of File Writing Methods
| Method | Best For | Writes |
|---|---|---|
| FileWriter | Simple text files | Characters |
| BufferedWriter | Large text files | Buffered characters |
| PrintWriter | Formatted text | Text |
| Files.write() | Small and medium files | Lines |
| Files.writeString() | Java 11+ | Entire String |
| FileOutputStream | Binary files | Bytes |
Using try-with-resources (Recommended)
The try-with-resources statement automatically closes resources.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedWriter writer =
new BufferedWriter(new FileWriter("students.txt"))) {
writer.write("Java File Handling");
} catch(IOException e) {
e.printStackTrace();
}
}
}
This approach is cleaner and prevents resource leaks.
Exception Handling
File-writing operations may throw exceptions.
Common exceptions include:
| Exception | Cause |
|---|---|
| IOException | General input/output error |
| FileNotFoundException | Invalid path or inaccessible file |
| SecurityException | Permission denied |
Example:
try {
FileWriter writer =
new FileWriter("students.txt");
} catch(IOException e) {
e.printStackTrace();
}
Always handle exceptions appropriately.
Real-Life Example
Suppose you are developing a student registration system.
Whenever a student registers, the application stores the details in a file.
import java.io.FileWriter;
import java.io.IOException;
public class StudentRegistration {
public static void main(String[] args) {
try (FileWriter writer =
new FileWriter("students.txt", true)) {
writer.write("Rahul Sharma\n");
System.out.println("Student saved successfully.");
} catch(IOException e) {
e.printStackTrace();
}
}
}
Many desktop and web applications use this approach for logging or exporting reports.
Advantages of Writing Files in Java
- Stores data permanently
- Supports text and binary files
- Multiple APIs for different requirements
- Easy integration with Java applications
- Platform independent
- Efficient for large files using buffered streams
Common Mistakes
1. Forgetting to Close the Writer
Incorrect:
FileWriter writer =
new FileWriter("students.txt");
Correct:
writer.close();
Or use try-with-resources.
2. Accidentally Overwriting Files
FileWriter writer =
new FileWriter("students.txt");
This replaces the existing contents.
To append:
FileWriter writer =
new FileWriter("students.txt", true);
3. Ignoring Exceptions
Always handle IOException.
Incorrect:
writer.write("Hello");
Correct:
try {
} catch(IOException e) {
}
4. Using Character Streams for Binary Data
Incorrect:
FileWriter writer =
new FileWriter("image.png");
Correct:
FileOutputStream output =
new FileOutputStream("image.png");
Character streams are intended for text, not binary data.
Best Practices
- Use BufferedWriter for large text files.
- Use PrintWriter for formatted output.
- Use Files.writeString() when working with Java 11 or later.
- Use FileOutputStream for binary files.
- Always use try-with-resources.
- Handle exceptions properly.
- Append to files when preserving existing data is required.
- Use meaningful file names and organize output directories.
Conclusion
Writing files is a fundamental part of Java programming and enables applications to store data permanently. Java provides several classes for writing files, including FileWriter, BufferedWriter, PrintWriter, FileOutputStream, and the modern Files API, allowing developers to choose the most suitable approach for their specific needs.
For text files, BufferedWriter and the Files API are excellent choices due to their simplicity and efficiency. For binary data, FileOutputStream is the preferred option. By following best practices such as using try-with-resources, handling exceptions properly, and selecting the appropriate file-writing method, you can build reliable, efficient, and maintainable Java applications that safely store data.