Read from File in Java: Explanation & Practice

Read contents of a file

Problem summary

Read and print the contents of a text file.

Starter code

import java.io.*;

public class Main {
    public static void main(String[] args) {
        // Read from input.txt (contains "Hello World")
        // Print contents
    }
}

Expected output and test cases

  • Read file contents
    Hello World

Hints

  1. Use FileReader or BufferedReader
  2. Read line by line with readLine()
  3. Check for null (end of file)

Related File I/O exercises

Practice all File I/O exercises · Run this idea in the Java compiler