Writing data to a file is a common operation in Java file handling. Java provides several classes and methods to write text or binary data into files depending on the type and size of the content.
- Character-based classes such as FileWriter and BufferedWriter are suitable for writing text data.
- FileOutputStream is useful when data needs to be written as bytes.
- The Files.writeString() method provides a simple way to write a String to a file and is available from Java 11 onwards.
Methods to Write into a File
There are several ways to write data into a file in Java, depending on the class or API being used.
1. Using writeString() Method
The writeString() method of the Files class was introduced in Java 11. It is used to write a character sequence directly to a file. It accepts the file path and the content to be written as the main parameters. It is a convenient choice when the content is relatively small.
Syntax:
Files.writeString(Path, CharSequence);
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
The FileWriter Class is a character-oriented writer used to write text data into a file. It is suitable when the data consists mainly of characters or strings. The write() method of FileWriter is used to write the specified content to the file. After writing, the writer should be closed to release the file resource.
Syntax:
FileWriter writer = new FileWriter("file.txt");
writer.write(data);
writer.close();
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
The BufferedWriter Class is used to write character data efficiently by maintaining a buffer. It can write characters, strings, and arrays to a character-output stream. BufferedWriter is commonly wrapped around a FileWriter to improve writing performance, especially when a larger amount of text needs to be written.
Syntax:
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
writer.write(data);
writer.close();
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:
4. Using FileOutputStream Class
The FileOutputStream Class is used to write byte-oriented data to a file. Unlike FileWriter and BufferedWriter, which are mainly used for character data, FileOutputStream can be used to write raw bytes.
Syntax:
FileOutputStream outputStream = new FileOutputStream("file.txt");
outputStream.write(byteData);
outputStream.close();
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: