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 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.io.*;
import java.nio.file.*;
import java.util.*;

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?
It generates some random value from given values. It will be helpful for our task.

We can easily complete the given task by creating a function and following the flow of data as mentioned-

  1. Under main, we will declare a variable named path which will save the route of our file.
  2. Use the parameter route and pass it to the function Line.
  3. Declare a list named l.
  4. use try and catch block
  5. Under the try block, we can use readAllLines() function and enter it into list l.
  6. Under the catch block, the code is defined to catch an error.
  7. Use Random() function and declare random variable.
  8. nextInt() will return next integer value.

So here is the flow of the program and as soon as nextInt() will be invoked, it will return any random integer and corresponding to that integer, list will be returned.

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

import java.io.*;
import java.nio.file.*;
import java.util.*;
class RandomFileReading {
    private static String Line(String route) {
        List<String> l;
        try {
            l = Files.readAllLines(Paths.get(route));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        Random random = new Random();
        return l.get(random.nextInt(l.size()));
    }

    public static void main(String[] args) {
     String route = new File("codespeedy.txt").getAbsolutePath();// whole path of the file has to be written within the double qoutes     
        String li= Line(route);
        System.out.println(li);
    }
}

 

Output:

Any random line from the file

You may also read:

One response to “Fetch Random Line From Text File In Java”

  1. G.Sandhya says:

    hey you why are you posting wrong code if you can put the correct code if not sit simply

Leave a Reply

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