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?
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();
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With