如何从.txt文件中读取随机文本?

时间:2022-08-30 09:01:02

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

我的计算机上有一个文件proxy.txt,所以我知道如何使用这个简单的方法顺序读取它:

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?

这个读取直到没有更多的代理,所以我想知道一个简单的方法来做同样的事情,但这次是随机的,我读到了一个名为“LineNumberReader”的方法,有人知道这个可以解释给我吗?

Thanks so much.

非常感谢。

1 个解决方案

#1


2  

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

#1


2  

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