You can do this:
- Get file size (in bytes)
- Select byte (randomly selected number in [0..file.length ()] -
RandomAccessFile ) - Look for this position in the file (
file.seek(number) ) - Look for a position immediately after the next
\n ( file.seek(1) ) - Read line (
file.readLine() )
eg...
This way you do not need to store anything.
An example of a theoretical snippet might look like this (contains some side effects):
File f = new File("D:/abc.txt"); RandomAccessFile file; try { file = new RandomAccessFile(f, "r"); long file_size = file.length(); long chosen_byte = (long)(Math.random() * file_size); file.seek(chosen_byte); for (;;) { byte a_byte = file.readByte(); char wordChar = (char)a_byte; if (chosen_byte >= file_size || wordChar == '\n' || wordChar == '\r' || wordChar == -1) break; else chosen_byte += 1; System.out.println("\"" + Character.toString(wordChar) + "\""); } int chosen = -1; if (chosen_byte < file_size) { String s = file.readLine(); chosen = Integer.parseInt(s); System.out.println("Chosen id : \"" + s + "\""); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
EDIT: Full working (theoretically) class
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class Main { public static void main(String[] args) throws Exception { File f = new File("D:/abc.txt"); RandomAccessFile file; try { file = new RandomAccessFile(f, "r"); long file_size = file.length();
Hope this is not too wrong as the implementation (I'm more C ++ these days) ...
source share