Java Programming Tutorials

Java programming tutorials with many code examples!

Java 8 read lines from a text file

Problem:

How to read lines from a text file in Java 8?

Solution:

Using methods from Files and Paths classes available in Java 8.

package com.farenda.solved;

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

public class JavaSolved {

    public static void main(String[] args) throws IOException {
        if (args.length == 0) {
            System.out.println("Run with a file as a parameter");
        } else {
            System.out.println("Reading from: " + args[0] + " using Java 8");
            // By default readAllLines() uses UTF-8 to load text
            for (String line : Files.readAllLines(Paths.get(args[0]))) {
                System.out.println(line);
            }
        }
    }
}

Compile the code with:

$> javac src/com/farenda/solved/*.java -d out

Result:

Running without arguments prints help:

$> java -cp out com.farenda.solved.JavaSolved
Run with a file as a parameter

Pass a file as an argument:

$> java -cp out com.farenda.solved.JavaSolved src/com/farenda/solved/JavaSolved.java
Reading from: src/com/farenda/solved/JavaSolved.java using Java 8
package com.farenda.solved;

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

public class JavaSolved {

    public static void main(String[] args) throws IOException {
        if (args.length == 0) {
            System.out.println("Run with a file as a parameter");
        } else {
            System.out.println("Reading from: " + args[0] + " using Java 8");
            // By default readAllLines() uses UTF-8 to load text
            for (String line : Files.readAllLines(Paths.get(args[0]))) {
                System.out.println(line);
            }
        }
    }
}
Share with the World!