Randomizing File Lines With Java
When building trivia quizzes or smoke tests, you may need to shuffle text lines before processing them. The snippet below uses the NIO Files
API and Collections.shuffle
for clarity.
Sample Code
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("test.txt"));
Collections.shuffle(lines);
lines.forEach(System.out::println);
}
Notes
- This approach loads the entire file into memory; for very large files, use a streaming algorithm with reservoir sampling.
- Seed
Collections.shuffle(lines, new Random(seed))
to reproduce the same order in tests. - Close resources or use try-with-resources when reading from channels or buffered readers directly.