Java Programming Tutorials

Java programming tutorials with many code examples!

Java 8 read file into a String

Problem:

How to read file into a String 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.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JavaSolved {

    // It's good to move such code to reusable methods
    private static String loadFile(String filename) throws IOException {
        // need to pass file encoding
        return new String(Files.readAllBytes(Paths.get(filename)),
                          StandardCharsets.UTF_8);
    }

    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");
            System.out.println(loadFile(args[0]));
        }
    }
}

Result:

  1. Create sample file books.txt with the content:
    "Thinking in Java"
    "Head First Java"
    "Design Patterns: Elements of Reusable Object-Oriented Software"
    "Applying UML and Patterns"
    "Agile Software Development, Principles, Patterns, and Practices"
    
  2. Compile the code:
    $> javac src/com/farenda/solved/*.java -d out
    
  3. Run with the file as parameter
    $> java -cp out com.farenda.solved.JavaSolved books.txt
    
    Reading from: books.txt using Java 8
    "Thinking in Java"
    "Head First Java"
    "Design Patterns: Elements of Reusable Object-Oriented Software"
    "Applying UML and Patterns"
    "Agile Software Development, Principles, Patterns, and Practices"
    
Share with the World!