Fetch Random Line From Text File In Java

In this instructional exercise, we will figure out how to get or fetch the random line from the text file in Java.
If if you don’t know the clue to fetch or get the random line from the text file through a simple java code then you are at the right spot to figure out your problem.

We are going to bring the irregular line from the content document through the java code.

Fetch Random Line From Text File In Java

Let’s learn with some easy examples.

At first, you have to import some packages to get the desired output. You can do it by:-




import java.util.*; //which includes, import java.util.Random; and import java.util.Scanner;
import java.io.*;  //includes, import java.io.File; and import java.io.FileNotFoundException;

Further, in the code,  you have to insert some functions of the random module available in the Random class to fetch the random lines from a text file or a number in general.

What Random module or class is?
Irregular class is a piece of java.util bundle. An example of java Random class is utilized to produce arbitrary numbers. This class gives a few techniques to create irregular quantities of a sorted integer, double, long, float and so on. If two Random examples have the same seed esteem, at that point, they will produce the same succession of irregular numbers.

Let’s understand the easy and simple example.
Here is the java code to achieve your desired goal:-

import java.util.Random;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class RandomFileReading {
    public static void main (String...args ) {
        try{
         File files = new File("codespeedy.txt");
        int c=0;
            Scanner scanner = new Scanner(files);
            while (scanner.hasNextLine()) {
                String l = scanner.nextLine();
                c++;
        Random random = new Random();
        int r = random.nextInt(c);
        System.out.println(c);
      }
       }catch (FileNotFoundException e) {
         System.out.println("error, please insert the valid files");
       }
    }
}

Output:

Hello, My name is shubham

You may also read:


Leave a Reply

Your email address will not be published. Required fields are marked *