How to get a random line from a file in Java

How to get a random line from a file in Java:

In this post, we will learn how to get a random line from a file in Java. The program will take the path of a file as input and print a line picking randomly from that file. With this program, you will learn how to read file contents and how to use Random module in Java.

Java program:

Below is the complete java program:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Random;

class Main {
    private static String getRandomLine(String path) {
        List<String> lines;
        try {
            lines = Files.readAllLines(Paths.get(path));
        } catch (IOException e) {
            return null;

        Random random = new Random();
        return lines.get(random.nextInt(lines.size()));

    public static void main(String[] args) {
        String path = new File("").getAbsolutePath() + "/src/sample.txt";
        String randomLine = getRandomLine(path);
        System.out.println("Random line : " + randomLine);


In this program,

  • getRandomLine is a method that will return one random line from the file.
  • path is the path to the file. I created a new file sample.txt with different contents. You can also create a different file and put that file path in the path variable.
  • The readAllLines method reads all lines of a file and returns a list of strings.
  • We are creating a Random object and using the nextInt method to get a random index value and returning that string at that index.


This will print a random line from the file.

You might also like: