Java FileWriter class in java is used to write character-oriented data to a file as this class is character-oriented class because of what it is used in file handling in java.
Methods: There are many ways to write into a file in java as there are many classes and methods which can fulfill the goal as follows:
- Using writeString() method
- Using FileWriter Class
- Using BufferedWriter Class
- Using FileOutputStream Class
Method 1: Using writeString() method
This method is supported by Java version 11. This method can take four parameters. These are file path, character sequence, charset, and options. The first two parameters are mandatory for this method to write into a file. It writes the characters as the content of the file. It returns the file path and can throw four types of exceptions. It is better to use when the content of the file is short.
Example
It shows the use of the writeString() method that is under Files class to write data into a file. Another class, Path, is used to assign the filename with a path where the content will be written. Files class has another method named readString() to read the content of any existing file that is used in the code to check the content is properly written in the file.
Java
// Java Program to write into a file // using writeString() method // Importing java NIO package import java.nio.file.Files; import java.nio.file.Path; // Importing class import java.io.IOException; // Class public class GFG { // Main driver method public static void main(String[] args) throws IOException { // Assign the content of the file String text = "Welcome to geekforgeeks\nHappy Learning!" ; // Define the file name of the file Path fileName = Path.of( "/Users/mayanksolanki/Desktop/demo.docx" ); // Write into the file Files.writeString(fileName, text); // Read the content of the file String file_content = Files.readString(fileName); // Print the content inside the file System.out.println(file_content); } } |
Welcome to geekforgeeks Happy Learning!
Method 2: Using FileWriter Class
If the content of the file is short, then using the FileWriter class to write in the file is another better option. It also writes the stream of characters as the content of the file like writeString() method. The constructor of this class defines the default character encoding and the default buffer size in bytes.
Example
The following example shows the use of the FileWriter class to write content into a file. It requires to create the object of the FileWriter class with the filename to write into a file. Next, the write() method is used to write the value of the text variable in the file. If any error occurs at the time of writing the file, then an IOexception will be thrown, and the error message will be printed from the catch block.
Java
// Java Program to write into a file // using FileWriterClass // Importing java input/output classes import java.io.FileWriter; import java.io.IOException; // Class public class GFG { // Main driver method public static void main(String[] args) { // Content to be assigned to a file // Custom input just for illustratinon purposes String text = "Computer Science Portal GeeksforGeeks" ; // Try block to check if excepion/s occurs try { // Create a FileWriter object // to write in the file FileWriter fWriter = new FileWriter( "/Users/mayanksolanki/Desktop/demo.docx" ); // Write into the file // The content taken above inside the string fWriter.write(text); // Printing the contents of a file System.out.println(text); // Close the file writer object fWriter.close(); // Display message to be printed on the console // window after successful execution of the // program System.out.println( "File is created successfully with the content." ); } // Catch block to handle if exception occurs catch (IOException e) { // Print the exception System.out.print(e.getMessage()); } } } |
File is created successfully with the content.
Method 3: Using BufferedWriter Class
It is used to write text to a character-output stream. It has a default buffer size, but the large buffer size can be assigned. It is useful for writing characters, strings, and arrays. It is better to wrap this class with any writer class for writing data to a file if no prompt output is required.
Example
Java
// Java Program to write into a File // using BufferedWriter Class // Importing java input output libraries import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; // Class public class GFG { // Main driver method public static void main(String[] args) { // Assign the file content // Custom contents taken as input to illustrate String text = "Computer Science Portal GeeksforGeks" ; // Try block to check if exceptions occurs try { // Step 1: Create an object of BufferedWriter BufferedWriter f_writer = new BufferedWriter( new FileWriter( "/Users/mayanksolanki/Desktop/demo.docx" )); // Step 2: Write text(content) to file f_writer.write(text); // Step 3: Printng the content inside the file // on the terminal/CMD System.out.print(text); // Step 4: Display message showcasing // succcessful execution of the program System.out.print( "File is created successfully with the content." ); // Step 5: Close the BufferedWriter object f_writer.close(); } // Catch block to handle if exceptions occcurs catch (IOException e) { // Print the exception System.out.print(e.getMessage()); } } } |
File is created successfully with the content.
The following example shows the use of BufferedWriter class to write into a file. It also requires to create the object of BufferedWriter class like FileWriter to write content into the file. But this class supports large content to write into the file by using a large buffer size.
Method 4: Using FileOutputStream Class
It is used to write raw stream data to a file. FileWriter and BufferedWriter classes are used to write only the text to a file, but the binary data can be written by using the FileOutputStream class.
To write data into a file using FileOutputStream class is shown in the following example. It also requires to create the object of the class with the filename to write data into a file. Here, the string content is converted into the byte array that is written into the file by using the write() method.
Example
Java
// Java Program to write into a file // using FileOutputStream Class // Importing java input output classes import java.io.FileOutputStream; import java.io.IOException; public class GFG { // Main driver method public static void main(String[] args) { // Assign the file content String fileContent = "Welcome to geeksforgeeks" ; // Try block to check if exception occurs try { // Step 1: Create an object of FileOutputStream FileOutputStream outputStream = new FileOutputStream( "file.txt" ); // Step 2: Store byte content from string byte [] strToBytes = fileContent.getBytes(); // Step 3: Write into the file outputStream.write(strToBytes); // Print the success message (Optional) System.out.print( "File is created successfully with the content." ); // Step 4: Close the object outputStream.close(); } // Catch block to handle the exception catch (IOException e) { // Print the exception System.out.print(e.getMessage()); } } } |
File is created successfully with the content.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.