Java MCQ: How does the Files.writeString() method introduced in Java 11 work?
Answer:
Explanation:
The Files.writeString() method, introduced in Java 11, writes a string to a file, overwriting any existing content in the file. This method provides a simple and efficient way to write text to a file, replacing the need for more complex I/O operations.
Here’s an example of using Files.writeString():
import java.nio.file.Files;
import java.nio.file.Path;
public class FilesWriteStringExample {
public static void main(String[] args) throws Exception {
Path filePath = Path.of("example.txt");
String content = "Hello, World!";
Files.writeString(filePath, content);
}
}
In this example, Files.writeString(filePath, content) writes the string “Hello, World!” to the file example.txt, overwriting any content that was previously in the file.
The Files.writeString() method is useful for quickly saving text data to a file, and it can be combined with Files.readString() for efficient file I/O operations in Java.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html