Java - view random strings

I am programming an Android application and want my program to read a random line of a file. How can I do it?

+8
java android file-io
source share
4 answers

To do this, you need fixed-length lines (in this case implementation details should be obvious) or information on how many lines there are (and, possibly, to improve performance) at what offsets inside the created file (sort index).

For small files, you can create such an index on demand when you need a random string. To do this efficiently for large files, you need to constantly maintain the index, possibly in a separate file.

If the lines tend to be about the same length, and you do not need perfect β€œrandomness,” you can also select a random byte offset within the file and scan the nearest line break.

+4
source share

You want a LineNumberReader .

You can use the setLineNumber() method to move to an arbitrary position in the file.

 LineNumberReader rdr; int numLines; Random r = new Random(); rdr.setLineNumber(r.nextInt(numLines)); String theLine = rdr.readLine(); 
+8
source share

Old fashioned answer: If you return zero, just remember 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; 
+2
source share

to get a random number, you can use the java Random class from the util package.

 Random rnd = new Random(); int nextRandomLineNumber = rnd.nextInt(); 

see http://developer.android.com/reference/java/util/Random.html

+1
source share

All Articles