Home page

Monday, June 12, 2023

Write data into text file in JAVA

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;


public class WriteToFileExample {

    public static void main(String[] args) {

        String data = "Hello, World!";


        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {

            writer.write(data);

            System.out.println("Data written to the file successfully.");

        } catch (IOException e) {

            System.out.println("An error occurred while writing to the file: " + e.getMessage());

        }

    }

}

In this example, we have a String variable data that contains the text we want to write to the file.

Inside the try block, we create a BufferedWriter object and pass a FileWriter object to its constructor. The FileWriter is initialized with the name of the file we want to write to ("output.txt" in this case).

We use the write() method of the BufferedWriter to write the data string to the file. Finally, we print a success message if the writing process is completed without any errors.

In case of any exception during the file writing process, we catch the IOException and print an error message indicating the cause of the exception.

Please note that the BufferedWriter and FileWriter classes are wrapped inside a try statement with resource declaration. This ensures that the resources are properly closed after use, even if an exception occurs.

After running the program, you will find the file "output.txt" created in the same directory as your Java source file, containing the text "Hello, World!".

Make sure you have the necessary write permissions for the directory where you are trying to create the file.

No comments:

Post a Comment