Close

Java 11 - java.nio.file.Files Changes

[Updated: Sep 30, 2018, Created: Sep 30, 2018]

Java 11 added following new methods in java.nio.file.Files class to directly read string from files and to directly write string to files:

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

Examples

package com.logicbig.example;

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

public class ReadWriteString {

  public static void main(String[] args) throws IOException {
      Path path = Files.writeString(
              Files.createTempFile("test", ".txt"), "test file content");
      System.out.println(path);
      String s = Files.readString(path);
      System.out.println(s);
  }
}
C:\Users\Joe\AppData\Local\Temp\test12716354840724176413.txt
test file content

Using Charset parameter:

package com.logicbig.example;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReadWriteString2 {

  public static void main(String[] args) throws IOException {
      Charset latinCharset = Charset.forName("ISO-8859-3");
      Path path = Files.writeString(
              Files.createTempFile("test", ".txt"), "test filum", latinCharset);
      System.out.println(path);
      String s = Files.readString(path, latinCharset);
      System.out.println(s);
  }
}
C:\Users\Joe\AppData\Local\Temp\test10271653105481172906.txt
test filum

Example Project

Dependencies and Technologies Used:

  • JDK 11
Java 11 - Files new methods Select All Download
  • java-11-files-changes
    • src
      • com
        • logicbig
          • example
            • ReadWriteString.java

    See Also