read lines of file randomly java

Solutions on MaxInterview for read lines of file randomly java by the best coders in the world

showing results for - "read lines of file randomly java"
Elisa
02 Jan 2019
1import java.io.*;
2import java.util.*;
3public class GetLine {
4  public static void main(String[] args) throws FileNotFoundException {
5     System.out.println("Random Line : "+randomLine());
6  }
7  public static void randomLine() throws FileNotFoundException {
8        File f = new File("file.txt");
9        String result = null;
10        Random rand = new Random();
11        int n = 0;
12        Scanner sc = new Scanner(f);
13        while (sc.hasNext()) {
14            ++n;
15            String line = sc.nextLine();
16            if (rand.nextInt(n) == 0)
17                result = line;
18        }
19        sc.close();
20    	return result;
21  }
22}