Leo Galindo
Leo Galindo

Reputation: 308

How can I read random text from .txt file?

I have a file proxy.txt in my computer, so I know how read it sequentially using this simple method:

FileReader  fl = new FileReader("C:/Users/Silver/Desktop/proxy.txt");
        BufferedReader br = new BufferedReader(fl);

        for(;;){
        String read = br.readLine();    
        System.out.println(read);
            Thread.sleep(100);
            if (read == null) {
                System.out.println("No More proxys");
                br.close();
            }

And this read until there are no more proxys, so I wanna know an easy method to do the same but this time randomly, I read about a method called "LineNumberReader" somebody that know about this can explain to me?

Thanks so much.

Upvotes: 0

Views: 1111

Answers (1)

XOR-Manik
XOR-Manik

Reputation: 503

Well You can read the text from the file to an Array List and then randomly read the strings from the list.

 BufferedReader(new FileReader("proxy.txt")); 
 List<String> lines = new ArrayList<String>();

 String line = reader.readLine();

 while( line != null ) {
     lines.add(line);
     line = reader.readLine(); }

  Random rand = new Random(); 
   String randomProxy = lines.get(rand.nextInt(lines.size()));

Upvotes: 2

Related Questions