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
- Store all lines in ArrayList
- Use Collections.reverse()
- Write reversed list to file
Related File I/O exercises
- Practice Count Words in File in Java
- Practice Search in File in Java
- Practice Merge Multiple Files in Java
Practice all File I/O exercises · Run this idea in the Java compiler