Java - File Input Output Read Files


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
Appends the written data to the existing file, if the file is opened for writing.
Creates a new file, if it does not exist.
Creates a new file, if it does not exist. If the file already exists, it fails.
Deletes the file when the stream is closed.
Keeps the contents of the file synchronized with the underlying storage.
Opens a file with a read access.

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.

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

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

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

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


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("");

    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) {
    } catch (NoSuchFileException e) {
      System.out.println(source.toAbsolutePath() + " does not exist.");
    } catch (IOException e) {