Answers for "read lines of file randomly java"

0

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;
  }
}
Posted by: Guest on June-03-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language