This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, March 9, 2023

Which classes are used to read and write data to file? Write a simple code to write a word to a file.

 In Java, there are several classes that can be used to read and write data to a file. The most commonly used classes are File, FileReader, FileWriter, BufferedReader, and BufferedWriter.

To write a word to a file in Java, we can use the FileWriter and BufferedWriter classes. Here is an example code that writes the word "Hello" to a file named "output.txt":

import java.io.*;
public class WriteToFileExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("output.txt");
            BufferedWriter bw = new BufferedWriter(writer);
            bw.write("Hello");
            bw.close();
            System.out.println("Word written to file.");
        } catch (IOException e) {
            System.err.println("Error writing to file: " + e.getMessage());
        }
    }
}

In this example, we create a FileWriter object to write to the file "output.txt". We then wrap the FileWriter in a BufferedWriter object to improve performance. The write() method of the BufferedWriter is used to write the word "Hello" to the file. Finally, we close the BufferedWriter and print a message to the console indicating that the word has been written to the file.

If the file "output.txt" does not exist, it will be created automatically. If it already exists, its contents will be overwritten by the word "Hello". If we run this program, we will see the following output:

Word written to file.

This output indicates that the word has been written to the file successfully.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget