1. Introduction
In this tutorial, we’ll discuss two methods added in Java 11 in Files class, readString()
and writeString()
.
2. Syntax
static String readString(Path path) | Reads all content from a file into a string, decoding from bytes to characters using the UTF-8 charset. |
static String readString(Path path, Charset cs) | Reads all characters from a file into a string, decoding from bytes to characters using the specified charset. |
static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption… options) | Write a CharSequence to a file. |
static Path writeString(Path path, CharSequence csq, OpenOption… options) | Write a CharSequence to a file. |
The readString()
method is intended for simple cases where it is appropriate and convenient to read the content of a file into a String. It is not intended for reading very large files. The method throws OutOfMemoryError
if the file is very large, for example larger than 2GB.
3. Example of readString()
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ReadStringExample { public static void main(String args[]) throws IOException { String contents = Files.readString(Paths.get("C:\\Users\\test.txt")); System.out.println(contents); } }
4. Example of writeString()
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ReadStringExample { public static void main(String args[]) throws IOException { Files.writeString(Paths.get("C:\\Users\\test.txt"), "append some message"); } }
5. Conclusion
These methods are part of the java.nio.file.Files
class, introduced in Java 11, and provide a modern approach to file handling, aligning with the language’s ongoing evolution towards more concise and expressive constructs.
By incorporating these methods into your projects, you can enhance the efficiency and readability of your file processing logic, ultimately leading to better maintainability and performance. Experiment with these methods and explore their optional parameters to fully leverage their capabilities in your applications.