Java Program to Write into a File
Last Updated :
23 Jul, 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 Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java In Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the java.lang.Object class. This allows you to invoke methods defined in Object (such as toStri
9 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
9 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read