Java – Reads from a file and displays random lines

Reads from a file and displays random lines… here is a solution to the problem.

Reads from a file and displays random lines

I’m trying to get my android app to read from a text file and randomly select an entry and then display it, how do I do that? I guess I have to use a buffer reader or input stream commands, but I don’t know how to use these, I tried googling but didn’t find much help.

As far as I understand (with some help) I have to read the text file, add it to the string? And use the following command to randomly select an entry

Random.nextInt(String[].length-1).

What should I do? :\I’m pretty new to all these buffer readers and stuff.

Solution

You are asking about 2 different operations here. Do not confuse them and thus confuse the problem. You want to know how:

  1. Read files from disk into a set of strings.
  2. Randomly select a string from a set of strings.

    // Read in the file into a list of strings
    BufferedReader reader = new BufferedReader(new FileReader("inputfile.txt"));
    List<String> lines = new ArrayList<String>();
    
    String line = reader.readLine();
    
    while( line != null ) {
        lines.add(line);
        line = reader.readLine();
    }
    
     Choose a random one from the list
    Random r = new Random();
    String randomString = lines.get(r.nextInt(lines.size()));
    

Related Problems and Solutions