Java MCQ: Which method is used to append data to an existing file in Java?
Answer:
Explanation:
The write()
method can be used to append data to an existing file in Java when used with the appropriate constructor of FileWriter
or BufferedWriter
. When creating a FileWriter
object, you can specify a second boolean parameter as true
to enable appending mode.
Here’s an example of how to append data to a file using FileWriter
:
import java.io.FileWriter;
import java.io.IOException;
public class AppendToFileExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt", true);
writer.write("Appending some text.");
writer.close();
System.out.println("Successfully appended to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
In this example, a FileWriter
object is created with the file name example.txt
, and the true
flag is passed as the second parameter to enable appending mode. The write()
method is then used to append the string “Appending some text.” to the file. Finally, the close()
method is called to close the file.
The BufferedWriter
class can also be used in a similar manner to append data to a file, often with better performance for large files due to its buffering capabilities. The key is to ensure that the appropriate constructor or method is used to enable appending mode.
Appending data to a file is a common requirement in applications that need to log data, add records to a file, or update existing content without overwriting the entire file. Understanding how to use the write()
method in appending mode is essential for such tasks.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html