java get random line from file efficiently code example

Example: read lines of file randomly java

import java.io.*;
import java.util.*;
public class GetLine {
  public static void main(String[] args) throws FileNotFoundException {
     System.out.println("Random Line : "+randomLine());
  }
  public static void randomLine() throws FileNotFoundException {
        File f = new File("file.txt");
        String result = null;
        Random rand = new Random();
        int n = 0;
        Scanner sc = new Scanner(f);
        while (sc.hasNext()) {
            ++n;
            String line = sc.nextLine();
            if (rand.nextInt(n) == 0)
                result = line;
        }
        sc.close();
    	return result;
  }
}

Tags:

Java Example