Java - Streams from Files

Introduction

The following code reads contents of a file using a stream.

It walks the entire file tree for the current working directory and prints the entries in the directory.

Demo

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    readFileContents("Main.java");
    listFileTree();// www  .  j a v a  2 s  .c  o m
  }

  public static void readFileContents(String filePath) {
    Path path = Paths.get(filePath);
    if (!Files.exists(path)) {
      System.out.println("The file " + path.toAbsolutePath() + " does not exist.");
      return;
    }

    try (Stream<String> lines = Files.lines(path)) {
      // Read and print all lines
      lines.forEach(System.out::println);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void listFileTree() {
    Path dir = Paths.get("");
    System.out.printf("%nThe file tree for %s%n", dir.toAbsolutePath());

    try (Stream<Path> fileTree = Files.walk(dir)) {
      fileTree.forEach(System.out::println);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result