Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Random line read

I am programing an Android app, and would like my program to read a random line of a file. How would I go about doing that?

like image 525
Wallter Avatar asked Jan 24 '11 18:01

Wallter


3 Answers

What you want is a LineNumberReader.

You can use the method setLineNumber() to move to a random position in the file.

LineNumberReader rdr;
int numLines;
Random r = new Random();
rdr.setLineNumber(r.nextInt(numLines));
String theLine = rdr.readLine();
like image 184
jjnguy Avatar answered Nov 20 '22 16:11

jjnguy


To do that, you need either fixed-length lines (the implementation details should be obvious in that case) or information about how many lines there are and (optionally, for better performance) at what offsets inside the file they begin (an index of sorts).

For small files, you can create such an index on demand whenever you need a random line. To do it efficiently for large files, you need to keep the index around persistently, perhaps in a separate file.

If lines tend to be roughly the same length and you don't need perfect "randomness", you could also pick a random byte offset inside the file and scan for the nearest line break.

like image 41
Michael Borgwardt Avatar answered Nov 20 '22 18:11

Michael Borgwardt


An old fashioned answer: If you get back a null, just recall the method

BufferedReader br = new BufferedReader(file);
Random rng = new Random (8732467834324L);
String s = br.readLine();
for ( ; s != null ; s = br.readLine())
    if (rng.nextDouble() < 0.2)
        break;
br.close();
return s;
like image 2
Manidip Sengupta Avatar answered Nov 20 '22 16:11

Manidip Sengupta