How does the Files.writeString() method introduced in Java 11 work?

Java MCQ: How does the Files.writeString() method introduced in Java 11 work?

a) It appends a string to an existing file
b) It writes a string to a file, overwriting any existing content
c) It writes a byte array to a file
d) It creates a new directory with the given string as the name

Answer:

b) It writes a string to a file, overwriting any existing content

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

Leave a Comment

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

Scroll to Top