How To Write To A File In Java

When working with files in Java, the process of saving data involves storing information in a specific file within a chosen directory. This functionality allows programs to generate, modify, and refresh both binary and text files. Java offers predefined classes to support efficient file handling and resource allocation. Proper exception handling is crucial during file write operations to prevent unexpected errors during runtime and maintain uninterrupted program execution.

In Java, there are various ways to write to a file because Java provides various classes and methods for file handing.

  • Using writeString Method
  • Using FileWriter Class
  • Using BufferedWriter Class
  • Using FileOutputStream Class
  • 1. Using writeString Method

The writeString function is implemented within the Files class which is part of the java.nio.file package. This feature was introduced starting from JDK 11. This function is responsible for writing a CharSequence to the specified file. It is essential to understand that the characters are transformed into bytes utilizing the UTF-8 character set.

There are two available versions of the writeString method.

Syntax:

Example

public static Path writeString (Path path, CharSequence csq, OpenOption... options) throws IOException

Parameters:

  • path: It defines the path of the target file in which we want to write.
  • csq: Character sequence to be written.
  • options: It specifies how the file is opened.

The method returns the path, requiring the first two parameters to be provided while the third one is discretionary. It may throw exceptions such as IllegalArgumentException, IOException, UnsupportedOperationException, and SecurityException.

Utilize the writeString function to perform file writing operations.

Example

Example

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.*;

public class Main

{

    public static void main(String[] args)

    {

        // Assigning the file content

        String txt = "Welcome to C# Programming\nHello World!\n WELCOME";

        try {

            BufferedReader buffread = new BufferedReader(new InputStreamReader(System.in));

            System.out.print("Enter the Path : ");

            // Reading the File name

            String path = buffread.readLine();

            // Create a BufferedWriter object

            BufferedWriter file_writer = new BufferedWriter(new FileWriter(path));

            // Write the text(content) to the file

            file_writer.write(txt);

            // displaying the content that is there in file

            System.out.print(txt);

            // Close the BufferedWriter object

            file_writer.close();

        }

        // Catch block to handle if exceptions occur

        catch (IOException ex) {

            System.out.print(ex.getMessage());

        }

    }

}

Output:

2. Using FileWriter Class

The Java FileWriter class is a part of the java.io package and is responsible for writing a sequence of characters to a file. It is typically utilized for writing brief content to a file. The constructors of the FileWriter class operate under the assumption that the default character encoding and default byte-buffer size are suitable.

We will utilize the FileWriter class for writing data to a file.

Example

Example

import java.io.*;

import java.nio.file.Files;

import java.nio.file.Path;

import java.util.*;

public class Main

{

    public static void main(String[] args) throws IOException 

    {

        // Data that has to be written in the file

        String txt = "Welcome to C# Programming\nHello World!\n WELCOME";

        BufferedReader buffread = new BufferedReader(new InputStreamReader(System.in));

        try {

            System.out.print("Enter the Path : ");  

            String path = buffread.readLine();

            // Create a FileWriter object so 

            // that we can write to the file.

            FileWriter fileWrite = new FileWriter(path);

            // Writing inside the file

            fileWrite.write(txt);

            // Displaying the contents of the file

            System.out.println(txt);

            // Closing the file writing connection

            fileWrite.close();

        }

          catch (IOException ex) {

            System.err.println("An error occurred in the file: " + ex.getMessage());

        }

    }

}

Output:

3. Using BufferedWriter Class

The Java BufferedWriter class belongs to the java.io package and is utilized for writing text to a character output stream. While it comes with a default buffer size, a larger size can also be assigned. This class facilitates writing characters, strings, and arrays. When immediate output is not essential, it is recommended to encapsulate this class within another writer class for efficient writing of data to a file.

Utilize the BufferedWriter class in a Java application to perform file writing operations.

Example

Example

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.*;

public class Main

{

    public static void main(String[] args)

    {

        // Assigning the file content

        String txt = "Welcome to C# Programming\nHello World!\n WELCOME";

        try {

            BufferedReader buffread = new BufferedReader(new InputStreamReader(System.in));

            System.out.print("Enter the Path : ");

            // Reading the File name

            String path = buffread.readLine();

            // Create a BufferedWriter object

            BufferedWriter file_writer = new BufferedWriter(new FileWriter(path));

            // Write the text(content) to the file

            file_writer.write(txt);

            // displaying the content that is there in file

            System.out.print(txt);

            // Close the BufferedWriter object

            file_writer.close();

        }

        // Catch block to handle if exceptions occurs

        catch (IOException ex) {

            System.out.print(ex.getMessage());

        }

    }

}

Output:

4. Using FileOutputStream Class

An output stream used for writing data to a File or a FileDescriptor is referred to as a file output stream. The Java FileOutputStream class is a part of the java.io package and is specifically designed for writing sequences of raw bytes, like binary or image data. If you need to write sequences of characters, it is recommended to utilize the FileWriter class instead.

Utilize the FileOutputStream class within a Java application to perform file writing operations.

Example

Example

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.*;

public class Main

{

    public static void main(String[] args)

    {

        // Assign the file content

        String fileContent = "Welcome to TechC# Tutorial\nHello World!\n WELCOME";

        FileOutputStream output = null;

        try {

            // Create an object of FileOutputStream

            output = new FileOutputStream("test.txt");

            // Store byte content from string

            byte[] strToBytes = fileContent.getBytes();

            // Write into the file

            output.write(strToBytes);

            System.out.print("File is created successfully with the content.");

        }

        catch (IOException ex) {

            System.out.print(ex.getMessage());

        }

        finally {

            // Close the object

            if (output != 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

                    output.close();

                }

                catch (IOException ex) {

                    System.out.print(ex.getMessage());

                }

            }

        }

    }

}

Output:

Input Required

This code uses input(). Please provide values below: