Java allows us to create files and write text into them.
We can use FileWriter, BufferedWriter,
and the Files class to write data.
Writing a file means storing information in a file. For example, a Java program can save a student's name, marks, or a message in a text file.
Example file content:
Welcome to Java!
This is my first file.
Java provides several classes and methods for writing data to files.
The FileWriter class is used to write characters
into a text file.
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (FileWriter writer =
new FileWriter("message.txt")) {
writer.write("Welcome to Java File Handling!");
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}
Output:
File written successfully.
This creates message.txt if it does not exist.
If the file already exists, its previous contents are
overwritten.
Use the newline character \n to place text
on separate lines.
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");
System.out.println("Student names saved.");
} catch (IOException e) {
System.out.println("Unable to write file.");
}
}
}
Content of students.txt:
Rahul
Amit
Priya
Appending means adding new content to the end of an existing file without removing its previous contents.
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (FileWriter writer =
new FileWriter("message.txt", true)) {
writer.write("\nThis line is added later.");
System.out.println("Data appended successfully.");
} catch (IOException e) {
System.out.println("Unable to append data.");
}
}
}
The second argument true enables append mode.
If the file does not exist, Java creates it.
new FileWriter("message.txt")
overwrites existing contents, while
new FileWriter("message.txt", true)
appends new data.
BufferedWriter writes text efficiently by
buffering characters. Its newLine() method
adds a line separator.
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("details.txt"))) {
writer.write("Name: Rahul");
writer.newLine();
writer.write("Course: Java");
writer.newLine();
writer.write("Marks: 85");
System.out.println("Details saved successfully.");
} catch (IOException e) {
System.out.println("Unable to write file.");
}
}
}
File content:
Name: Rahul
Course: Java
Marks: 85
You can use the File class to create a file
explicitly before writing data.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
File file = new File("newfile.txt");
if (file.createNewFile()) {
System.out.println("File created.");
} else {
System.out.println("File already exists.");
}
try (FileWriter writer = new FileWriter(file)) {
writer.write("Hello from Java!");
}
System.out.println("Data written successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}
The createNewFile() method creates a new,
empty file only if it does not already exist.
Java 11 and later provide Files.writeString()
for writing a string to a file.
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
Path path = Path.of("message.txt");
Files.writeString(
path,
"Hello! This file was written using Files."
);
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("Unable to write file.");
}
}
}
This method creates the file if it does not exist and replaces its contents if it already exists.
Use StandardOpenOption.APPEND to add text
to an existing file.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
Path path = Path.of("message.txt");
Files.writeString(
path,
"\nNew content added.",
StandardOpenOption.CREATE,
StandardOpenOption.APPEND
);
System.out.println("Content appended.");
} catch (IOException e) {
System.out.println("Unable to append content.");
}
}
}
CREATE allows Java to create the file if it
does not exist. APPEND adds content at the end.
The following example saves student information in a text file.
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String name = "Rahul";
int marks = 90;
String course = "Java";
try (FileWriter writer =
new FileWriter("student.txt")) {
writer.write("Name: " + name + "\n");
writer.write("Marks: " + marks + "\n");
writer.write("Course: " + course + "\n");
System.out.println("Student information saved.");
} catch (IOException e) {
System.out.println("Unable to save student information.");
}
}
}
File content:
Name: Rahul
Marks: 90
Course: Java
You can write multiple lines using
Files.write() and a list of strings.
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
List<String> names =
List.of("Rahul", "Amit", "Priya");
try {
Files.write(Path.of("names.txt"), names);
System.out.println("Names saved successfully.");
} catch (IOException e) {
System.out.println("Unable to save names.");
}
}
}
Each string is written as a separate line. The file is created if necessary, and an existing file is normally truncated before the new content is written.
| Writing | Appending |
|---|---|
| Replaces existing content by default. | Keeps existing content and adds more. |
Uses new FileWriter("data.txt"). |
Uses new FileWriter("data.txt", true). |
| Useful for saving fresh content. | Useful for adding records or log entries. |
IOException when writing files.hello.txt and write a welcome message.FileWriter.BufferedWriter.Files.writeString().1. Which class can write characters to a text file?
2. What does the second argument true mean in FileWriter?
3. Which method writes a string to a file in Java 11 and later?