{

Java 11 Features - java.nio.file.Files class new Methods | Read/write a string from to a file


Java 11 Features - java.nio.file.Files class new Methods

In this blog post, We are going to learn the new methods added to the java.nio.file.Files class.

What is java.nio.file.Files class in java11

This class is used for doing operations with files and directories of a file system.

It provides various static methods for doing it.

with Java 11, the Files class added the below methods for converting file content to/from strings.

It introduced the following Java 11 Files and new methods.

  • String Files.readString(Path path)
  • String Files.readString(Path, Charset)
  • Path Files.write(Path, CharSequence, OpenOptionā€¦)
  • Path Files.write(Path, CharSequence, Charset, OpenOptionā€¦)

With these methods, We can achieve the following things.

  • How to Read a string from a file
  • How to Write a String into a file

These are commonly used operations when dealing with the file system.

How to Read String content from a File before java11?

This example explains How to read the content of a file. First, read all bytes from a file using a readAllBytes method which returns a Byte Array Next, Convert this to a String with a byte array as a parameter for a string constructor.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Files1 {
    public static void main(String[] args) {
        // First Create a Path Object  
        Path path = Paths.get("b://files1.txt");
        //Create a file  
        try {
            byte[] bs = Files.readAllBytes(path);
            System.out.println(new String(bs));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 

Output:

This is test content  

As seen above, We read from the file and convert bytes to the String method.

Alternatively, the Same can be done using the readString() method.

Read from a file using readString() method

This method reads all the content of a file and returns it as a string.

It also contains an overloaded method for Charset for decoding bytes to characters.

This method throws an Exception in the below cases.

  • java.nio.file.NoSuchFileException: if the file does not exist on a file system
  • java.io.IOException: This exception throws during IO operations of transferring the file to the String
  • java.lang.OutOfMemoryError: This exception throws when the file size is large i.e 2GB file size
  • java.lang.SecurityException: This exception throws when there are permissions access issues for accessing files Syntax.

Here is a Syntax

 public static String readString(Path path) throws IOException   
 public static String readString(Path path, Charset cs) throws IOException 

Here is an example that explains about

  • read file content into a string
  • read file content into String using UTF-8 Decoding
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Files1 {
    public static void main(String[] args) {
        // First Create a Path Object  
        Path path = Paths.get("b://files1.txt");
        //Read a file  
        try {
            String string = Files.readString(path);
            System.out.println(string);
            String string1 = Files.readString(path,StandardCharsets.UTF_8);
            System.out.println(string1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}  

Output:

Test content from a file  
Test content from a file  

How to write a string to a file using the writeString() method?

This method is used to write a string to a File on the filesystem

This method throws an Exception in the below cases java. lang.IllegalArgumentException - This will be thrown when invalid options are provided

  • java.io.IOException: This exception throws when during IO operations error of writing a string to file
  • java.lang.UnsupportedOperationException: This exception throws when unsupported operations are provided
  • java.lang.SecurityException: This exception throws when there are permissions access issues for accessing files

Following is a Signature

public static Path writeString(Path path, CharSequence csq, OpenOption... options) throws IOException  
public static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options)  

Example:

This example shows, how to write a string into file write a string into a file using UTF-8 Decoding.

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Files1 {
    public static void main(String[] args) {
        // First Create a Path Object  
        Path path = Paths.get("b://files1.txt");
        CharSequence sequenceString = "new string adding content in to a file";

        //Read a file  
        try {
            Path newPath= Files.writeString(path,sequenceString);
            String string1 = Files.readString(newPath,StandardCharsets.UTF_8);
            System.out.println(string1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}  

Output:

new string adding content into a file  

Conclusion

Learned new Files methods with examples introduced in the java 11 version.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.