-
Hajipur, Bihar, 844101
In Java, working with files doesn’t stop at creating them. Once a file exists, you’ll often need to write data into it—such as text, logs, configuration details, or even user input. Java offers multiple ways to create and write files using different classes, each suited for specific needs.
In this tutorial, we’ll explore how to create new files and write content into them using the classes from both the java.io and java.nio.file packages.
Before writing data, you need a file to exist. If the file doesn’t already exist, Java can create it automatically when you try to write into it. You can write data in several ways—using classes like:
FileWriter
BufferedWriter
PrintWriter
FileOutputStream
Files.write() (from java.nio.file)
Each of these classes helps you write text or binary data to files, depending on what you’re trying to do.
The FileWriter class is one of the simplest ways to write character data into a file. If the file doesn’t exist, it will be created automatically.
Here’s an example:
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("notes.txt");
writer.write("Java file handling is very useful.\n");
writer.write("We can easily write text to a file using FileWriter.");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Explanation:
FileWriter automatically creates the file if it doesn’t exist.
The write() method adds the given text into the file.
It’s important to close the writer using writer.close() to ensure that data is saved properly.
By default, FileWriter overwrites the file. If you want to add new content without deleting the old one, you can enable append mode by passing true as the second parameter:
FileWriter writer = new FileWriter("notes.txt", true);
writer.write("\nThis line is appended to the file.");
writer.close();
This keeps the existing data intact and simply adds new content at the end.
When you’re writing large amounts of data, it’s better to use BufferedWriter because it temporarily stores data in a buffer before writing it to the file, making the process faster.
Example:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample {
public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("log.txt"));
writer.write("This is the first line.");
writer.newLine();
writer.write("BufferedWriter helps improve performance.");
writer.close();
System.out.println("Data written successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
}
Key Point:
The newLine() method adds a line break, which makes the file easier to read.
PrintWriter is another useful class that allows you to write formatted text into files. It’s similar to System.out.println() but writes directly into a file.
Example:
import java.io.PrintWriter;
import java.io.IOException;
public class PrintWriterExample {
public static void main(String[] args) {
try {
PrintWriter output = new PrintWriter("output.txt");
output.println("This is a test message.");
output.println("PrintWriter makes writing text simple.");
output.close();
System.out.println("File created and data written successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
You can use print(), println(), or even formatted methods like printf() with this class.
So far, we’ve written text data (characters). If you want to write binary data such as images, bytes, or encoded text, you can use FileOutputStream.
Example:
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamExample {
public static void main(String[] args) {
String data = "Java FileOutputStream example.";
try {
FileOutputStream output = new FileOutputStream("data.txt");
output.write(data.getBytes());
output.close();
System.out.println("Binary data written successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Here, getBytes() converts the string into a sequence of bytes that can be written to the file.
The modern and most convenient way to write data is using the Files class from the java.nio.file package. It provides a simple one-line method to write data into a file.
Example:
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
public class NioWriteExample {
public static void main(String[] args) {
Path path = Paths.get("niofile.txt");
List<String> lines = List.of("Hello, this is the first line.", "This is written using NIO Files class.");
try {
Files.write(path, lines);
System.out.println("File created and data written successfully using NIO.");
} catch (IOException e) {
System.out.println("Error writing to file.");
e.printStackTrace();
}
}
}
You can also use Files.writeString() (available from Java 11) to write a single string directly:
Files.writeString(Paths.get("sample.txt"), "This is another example using writeString().");
File operations often fail if the file path is wrong, permissions are missing, or storage is full. Always handle IOException using a try-catch block. You can also use the try-with-resources statement (introduced in Java 7), which automatically closes the file when done:
import java.io.FileWriter;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("autoClose.txt")) {
writer.write("This file is written using try-with-resources.");
System.out.println("Data written safely.");
} catch (IOException e) {
System.out.println("Error while writing file.");
e.printStackTrace();
}
}
}
This is the safest and cleanest way to handle file writing.
Always close the stream:
Closing the stream ensures all data is saved properly and prevents file corruption.
Use buffering for large files:
Classes like BufferedWriter and BufferedOutputStream improve performance significantly.
Avoid overwriting accidentally:
Check if the file already exists before writing.
Use try-with-resources:
It’s the safest and easiest way to manage file resources.
Handle exceptions properly:
Always use meaningful error messages when handling file operations.
Creating and writing files in Java is simple and flexible. You can use:
FileWriter for quick text writing
BufferedWriter for efficient large data writing
PrintWriter for formatted output
FileOutputStream for binary data
Files.write() or Files.writeString() for a modern, cleaner approach
Each method has its use case, and understanding when to use which makes you more confident in handling files in Java.
In the next tutorial, we’ll learn how to read data from files using different approaches.
Write a Java program using FileWriter to create a file named info.txt and write two lines of text into it.
Write a Java program that appends a new line of text to an existing file named log.txt without overwriting its existing content.
Create a Java program using BufferedWriter to write five lines of user-defined text into a file called messages.txt.
Write a Java program using PrintWriter that writes formatted output (for example, name and marks of students) into a file named students.txt.
Write a program using FileOutputStream that writes the string "Java File Handling Example" as bytes into a file named binarydata.txt.
Write a Java program using Files.write() (NIO package) to create a new file named notes.txt and write a list of three strings into it.
Write a program using Files.writeString() (Java 11+) to create a file named summary.txt and write a single paragraph of text.
Write a Java program that first checks if a file named report.txt exists. If it doesn’t, create it and then write “Report File Created Successfully” inside.
Create a Java program using a try-with-resources statement that writes “Auto Close Example” into a file named auto.txt.
Write a Java program that uses FileWriter in append mode to record the current date and time each time the program runs in a file named logfile.txt.