Reverse File Lines in Java: Explanation & Practice

Reverse the order of lines in a file

Problem summary

Read a file and write lines in reverse order to a new file.

Starter code

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Read lines, reverse order, write to new file
        // Print reversed lines
    }
}

Expected output and test cases

  • Reversed order
    Line 3
    Line 2
    Line 1
  • Single line
    Only line
  • ABC reversed
    C
    B
    A

Hints

  1. Store all lines in ArrayList
  2. Use Collections.reverse()
  3. Write reversed list to file

Related File I/O exercises

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