Java 11

Java 11 – File APIs

Java 11 introduced an easy way to read and write files by providing new overloaded methods without writing much boiler plate code.

Consider the following example −

Java11Files.java

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

public class Java11Files {
	
	public static void main(String[] args) {
		try {
			 // 1. Write string to sample.txt file
	         Path filePath = Files.writeString(
	            Path.of(File.createTempFile("sample", ".txt").toURI()),
	            "Welcome to HiTechPoints", 
	            Charset.defaultCharset(), StandardOpenOption.WRITE);

	         // 2. Read text from sample.txt file
	         String fileContent = Files.readString(filePath);
	         System.out.println(fileContent);
	      } catch (IOException e) {
	         e.printStackTrace();
	      }
	}
}

Output

Welcome to HiTechPoints

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs