Which method is used to write data to a file in Java?

Java MCQ: Which method is used to write data to a file in Java?

a) writeFile()
b) write()
c) writeBytes()
d) writeToFile()

Answer:

b) write()

Explanation:

The write() method in Java is commonly used to write data to a file. This method is available in several classes, such as FileWriter, BufferedWriter, and OutputStream, each serving different use cases. For text files, FileWriter or BufferedWriter is typically used.

Here’s an example of how to use FileWriter to write text to a file:

import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("example.txt");
            writer.write("Hello, World!");
            writer.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

In this example, FileWriter is used to create a FileWriter object that points to the file example.txt. The write() method is then called to write the string “Hello, World!” to the file. Finally, the close() method is called to close the file, ensuring that all resources are released.

The write() method can also be used with BufferedWriter, which wraps a FileWriter and provides efficient writing of text. This is useful for writing large amounts of data to a file, as BufferedWriter reduces the number of I/O operations by buffering the data.

Overall, the write() method is a fundamental tool for writing data to files in Java, and understanding how to use it is essential for file handling operations.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top