Java Program to Write into a File
Last Updated :
10 Jan, 2025
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:
- Using writeString() method
- Using FileWriter Class
- Using BufferedWriter Class
- 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:
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:
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:
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:
Screenshot of the File:
Similar Reads
Java Program to Write Data to Temporary File A Temporary file or a Temp file is a file that is created in order to hold information for some time while a file is being created or modified. After the successful execution of the program or after the program is closed, the temporary file is deleted. Other advantages of having a temporary file are
3 min read
Java Program to Read a File to String There are multiple ways of writing and reading a text file. This is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Given a text file, the task is to read the contents
8 min read
How to Read and Write Binary Files in Java? The Binary files contain data in a format that is not human-readable. To make them suitable for storing complex data structures efficiently, in Java, we can read from and write to binary files using the Input and Output Streams.In this article, we will learn and see the code implementation to read a
2 min read
Java Program to Save a String to a File A demo file on the desktop named 'gfg.txt' is used for reference as a local directory on the machine. Creating an empty file before writing a program and give that specific path of that file to the program. Methods: Using writeString() method of Files classUsing write() method of Files classUsing wr
6 min read
Java Program to Create a New File There are two standard methods to create a new file, either directly with the help of the File class or indirectly with the help of the FileOutputStream class by creating an object of the file in both approaches.Methods to Create Files in JavaThere are two methods mentioned belowUsing the File Class
4 min read
Java File Handling Programs Java is a programming language that can create applications that work with files. Files are containers that store data in different formats, such as text, images, videos, etc. Files can be created, read, updated, and deleted using Java. Java provides the File class from the java.io package to handle
3 min read