Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read from file and display random line

Im trying to get my android application to read from a text file and randomly chose an entry and then display it, How do i go about doing this? I think i have to use the buffer reader or input stream commands, but i have no idea how to use these, i've tried googling but havent found much help.

As far as i know (and with some help) i have to read the text file, add it to a string? and use the following command to randomly pick an entry

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

How do i go about doing this? :\ im quite new to all this bufferreader stuff etc.

like image 391
Wassif Avatar asked Feb 04 '26 14:02

Wassif


1 Answers

You are asking about 2 different operations here. Don't cloud up the problem by muddling them together. You want to know how to:

  1. Read a file from disk into a group of strings.
  2. Randomly choose 1 string from a group 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()));
    
like image 133
wolfcastle Avatar answered Feb 06 '26 06:02

wolfcastle