Open In App

Java Program to Write into a File

Last Updated : 10 Jan, 2025
Suggest changes
Share
Like Article
Like
Report

FileWriter class in Java is used to write character-oriented data to a file as this class is character-oriented because it is used in file handling in Java. 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:

  1. Using writeString() method
  2. Using FileWriter Class
  3. Using BufferedWriter Class
  4. Using FileOutputStream Class

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: The below example illustrates the use of writeString() method to write data into a file.

Java
// Write File using // writeString Method import java.io.*; import java.nio.file.Files; import java.nio.file.Path; public class WriteString {  public static void main(String[] args)  throws IOException   {    // Data to be written in file  String text = "Welcome to GeeksforGeeks\nHappy Learning!";  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  System.out.print("Enter the Path : ");  String path = br.readLine();  // Defining the file name of the file  Path fileName = Path.of(path);  try {  Files.writeString(fileName, text);  // Reading the content of the file  String fileContent = Files.readString(fileName);  // Printing the content inside the file  System.out.println(fileContent);  }   catch (IOException e) {  System.err.println("An error occurred: " + e.getMessage());  }  } } 

Output:

WriteString


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 below example illustrates the use of the FileWriter class to write content into a file.

Java
// Write into a File // using FileWriterClass import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class FileWriterClass  {  public static void main(String[] args)  {  // Data to be written in file  String text = "Welcome to GeeksforGeeks\nHappy Learning!";  // Try block to check if exception occurs  try {  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  System.out.print("Enter the Path : ");    // Reading File name  String path = br.readLine();  // Create a FileWriter object  // to write in the file  FileWriter fWriter = new FileWriter(path);  // Writing into file  fWriter.write(text);  // Printing the contents of a file  System.out.println(text);  // Closing the file writing connection  fWriter.close();  }  // Catch block to handle if exception occurs  catch (IOException e) {  // Print the exception  System.out.print(e.getMessage());  }  } } 

Output:

FileWriterClass


3. Using BufferedWriter Class

It is used to write text to a character-output stream. It has a default buffer size, but a 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: The below example illustrates the use of the BufferedWriter class to write content into a file.

Java
// Write into a File // Using BufferedWriter Class // Importing java input output libraries import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class BufferedWriterClass  {  public static void main(String[] args)  {  // Assigning the file content  String text = "Welcome to GeeksforGeeks\nHappy Learning!";  // Try block to check for exceptions  try {  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  System.out.print("Enter the Path : ");    // Reading File name  String path = br.readLine();  // Create an object of BufferedWriter  BufferedWriter f_writer = new BufferedWriter(new FileWriter(path));  // Write text(content) to file  f_writer.write(text);  // Printing the content inside the file  // on the terminal/CMD  System.out.print(text);  // Close the BufferedWriter object  f_writer.close();  }  // Catch block to handle if exceptions occurs  catch (IOException e) {  // Print the exception on console  // using getMessage() method  System.out.print(e.getMessage());  }  } } 

Output:

BufferedWriter


The following example shows the use of BufferedWriter class to write into a file. It also requires creating 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.

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.

Example: Demonstrate to write data into a file using FileOutputStream class is shown in the following 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 FileOutputStreamClass {  // Main driver method  public static void main(String[] args)  {  // Assign the file content  String fileContent = "Welcome to GeeksforGeeks\n"  + "Happy Learning!";    FileOutputStream outputStream = null;  // Try block to check if exception occurs  try {  // Step 1: Create an object of 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.");  }  // Catch block to handle the exception  catch (IOException e) {  // Display the exception/s  System.out.print(e.getMessage());  }  // finally keyword is used with in try catch block  // and this code will always execute whether  // exception occurred or not  finally {  // Step 4: Close the object  if (outputStream != null) {  // Note: Second try catch block ensures that  // the file is closed even if an error  // occurs  try {  // Closing the file connections  // if no exception has occurred  outputStream.close();  }  catch (IOException e) {  // Display exceptions if occurred  System.out.print(e.getMessage());  }  }  }  } } 

Output:

FileOutputStream

Screenshot of the File:

File Content

Similar Reads

Article Tags :
Practice Tags :