Java11 introduced two methods in Files Class
- readString()
- writeString()
How to read text file readString example?
Java11 provides Files readString method
that read the string into a file with given encoding.
Syntax:
readString
read the file content as bytes and convert to String using UTF-8 encoding
public static String readString(Path path) throws IOException
public static String readString(Path path, Charset cs) throws IOException
In the first method, Read the file content into a string using default charset.
Arguments:
This method takes java.nio.file.path
as an argument
Return: Return the string with all file content.
Throws: IOException
for IO exceptions, OutOfMemoryError
for reading larger files size greater than 2GB.
CharSet is an CharSet to read
Here is an Java File Read example
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaRead {
public static void main(String[] args) {
//Path object with given file in File System
Path path
= Paths.get("a:\\", "data.txt");
try {
String content = Files.readString(path);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
It prints the content of the file
Java writeString example
This is an example of writing string into a test file in java11.
Java11 provides Files writeString method
that writes the string into a file.
public static Path writeString(Path path, CharSequence csq, OpenOption... options)
public static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options)
Files WriteString
has two overrided versions.
First, path writes a string into a file using Path and default Charset.
Second , writes a string into a file using CharSet and Options.
Here is an Java File Write example
Arguments: path: Path of an file in File System. CharSequence: charSequence or actual content in a string, write to a file. OpenOption: StandardOpenOption is an class that used here
It has below options
- READ
- WRITE
- APPEND
- TRUNCATE_EXISTING
- CREATE
- CREATE_NEW
- DELETE_ON_CLOSE
- SPARSE
- SYNC
- DSYNC StandardOpenOption.NEW used in the below example if new file need to create.
Here is an Java File Write example
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class JavaWrite {
public static void main(String[] args) {
//Path object with given file in File System
Path path
= Paths.get("a:\\", "test.txt");
try {
Files.writeString(path, "Test content inserted into a file", StandardOpenOption.CREATE);
String content = Files.readString(path);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}