Java - File Input Output Read Files

Introduction

Files class contains the following methods to read the contents of a file as bytes and lines of text:

      
static List<String> readAllLines(Path path)
static List<String> readAllLines(Path path, Charset cs)
      static byte[] readAllBytes(Path path)

All three methods may throw an IOException.

  • readAllBytes() method reads all bytes from a file.
  • readAllLines() method reads the entire contents of a file lines of text.
  • readAllLines() method uses a carriage return, a line feed, and a carriage returned followed by a line feed as a line terminator.

The lines returned do not contain the line terminator.

Without charset parameter this method assumes the contents of the file in the UTF-8 charset.

readAllBytes() and readAllLines() method class are intended to read the contents of a small file.

Both methods take care of opening/closing the file before/after reading.

List of OpenOption Type Values That are Enum Constants in the StandardOpenOption Enum

StandardOpenOption Constant
Description
APPEND
Appends the written data to the existing file, if the file is opened for writing.
CREATE
Creates a new file, if it does not exist.
CREATE_NEW
Creates a new file, if it does not exist. If the file already exists, it fails.
DELETE_ON_CLOSE
Deletes the file when the stream is closed.
DSYNC
Keeps the contents of the file synchronized with the underlying storage.
READ
Opens a file with a read access.
SPARSE

If it is used with the CREATE_NEW option, it is a hint to the file system that the new
file should be a sparse file.
SYNC

Keeps the content and the metadata of the file synchronized with the
underlying storage.
TRUNCATE_EXISTING

Truncates the length of an existing file to zero if the file is opened for a write
access.
WRITE
Opens a file for a write access.

The following code demonstrates how to read and display the contents of a file Main.java in your default directory.

The program displays an error message if the file does not exist.

Demo

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    Charset cs = Charset.forName("US-ASCII");
    Path source = Paths.get("Main.java");

    try {/*w w w .  j  av  a2s  . co m*/
      // Read all lines in one go
      List<String> lines = Files.readAllLines(source, cs);

      // Print each line
      for (String line : lines) {
        System.out.println(line);
      }
    } catch (NoSuchFileException e) {
      System.out.println(source.toAbsolutePath() + " does not exist.");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result

Exercise