In my previous blog, I covered how to read data from a text file using Java. If you haven't read it yet, check it out here:Java File Handling: From Text File to ArrayList
In the previous section, we saw how to read employee details from a text file using FileReader and BufferedReader.
Now let's see how to write data into a file using Java.
To write data into a file, we use three important classes:
- File: Represents the file and its location.
- FileWriter: Used to write characters into a file.
- BufferedWriter: Helps us write data efficiently.
Complete Code
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class EmployeeController {
public static void main(String[] args) {
File note = new File("empData1.txt");
try {
FileWriter pen = new FileWriter(note, true);
BufferedWriter writer = new BufferedWriter(pen);
writer.write("ghi");
writer.write("jkl");
writer.close();
} catch (IOException io) {
System.out.println("IO exception");
}
}
}
Understanding the Code Bit by Bit
1. Creating a File Object
File note = new File("empData1.txt");
First, we create a File object and pass the file name.
This represents the location of the file where we want to write our data.
2. Using FileWriter
FileWriter pen = new FileWriter(note, true);
FileWriter is used to write characters into a file.
Here, we pass two arguments:
-
note– The File object representing the file. -
true– Tells Java to append the data instead of overwriting the existing content.
One important thing to remember:
- If we pass
true, new data is added at the end of the existing content. - If we pass
falseor don't provide the second argument, the existing content is overwritten.
3. Using BufferedWriter
BufferedWriter writer = new BufferedWriter(pen);
BufferedWriter takes the FileWriter object as an argument.
It helps us write data efficiently by buffering the characters before writing them to the file.
4. Writing Data into the File
writer.write("ghi");
writer.write("jkl");
The write() method is used to write data into the file.
Here, we are writing two Strings: "ghi" and "jkl".
The output inside the file will be:
ghijkl
Notice that the write() method doesn't automatically move to the next line.
If we want each String on a separate line, we can use:
writer.write("ghi");
writer.newLine();
writer.write("jkl");
5. Closing the Writer
writer.close();
Once writing is completed, we close the BufferedWriter to release the resources.
Conclusion
FileWriter and BufferedWriter are used to write data into files in Java.
FileWriter handles writing characters, while BufferedWriter helps make the writing process more efficient.
Using these classes, we can easily write or append data to an existing text file.
Top comments (0)