Tyler Wall
Tyler Wall

Reputation: 3788

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?

Upvotes: 8

Views: 1790

Answers (4)

Manidip Sengupta
Manidip Sengupta

Reputation: 3611

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;

Upvotes: 2

Michael Borgwardt
Michael Borgwardt

Reputation: 346270

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.

Upvotes: 4

Lars
Lars

Reputation: 575

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

Upvotes: 1

jjnguy
jjnguy

Reputation: 138874

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();

Upvotes: 8

Related Questions