简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM