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?
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.
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.
.txt
file (or .bin whatever). –
Gulgee 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;
to obtain a random number you can use java's Random
class from the util package.
Random rnd = new Random();
int nextRandomLineNumber = rnd.nextInt();
see http://developer.android.com/reference/java/util/Random.html
Random()
–
Gulgee © 2022 - 2024 — McMap. All rights reserved.
.txt
file (or .bin whatever). – Gulgee