如何在Java中获取文本文件的随机行? [英] How to get a random line of a text file in Java?

查看:327
本文介绍了如何在Java中获取文本文件的随机行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说有一个太大的文件无法存储到内存中.如何从中获得随机线?谢谢.

Say there is a file too big to be put to memory. How can I get a random line from it? Thanks.

更新: 我想让每条线相等的可能性.

Update: I want to the probabilities of getting each line to be equal.

推荐答案

这是一个解决方案.看看做真实事情的choose()方法(main()方法反复练习choose(),以证明分布确实非常均匀).

Here's a solution. Take a look at the choose() method which does the real thing (the main() method repeatedly exercises choose(), to show that the distribution is indeed quite uniform).

这个想法很简单:当您阅读第一行时,有100%的机会被选为结果.当您阅读第二行时,有50%的机会替换第一行.当您阅读第三行时,它有33%的机会成为结果.第四行有25%,依此类推....

The idea is simple: when you read the first line it has a 100% chance of being chosen as the result. When you read the 2nd line it has a 50% chance of replacing the first line as the result. When you read the 3rd line it has a 33% chance of becoming the result. The fourth line has a 25%, and so on....

import java.io.*;
import java.util.*;

public class B {

  public static void main(String[] args) throws FileNotFoundException {
     Map<String,Integer> map = new HashMap<String,Integer>();
     for(int i = 0; i < 1000; ++i)
     {
        String s = choose(new File("g:/temp/a.txt"));
        if(!map.containsKey(s))
           map.put(s, 0);
        map.put(s, map.get(s) + 1);
     }

     System.out.println(map);
  }

  public static String choose(File f) throws FileNotFoundException
  {
     String result = null;
     Random rand = new Random();
     int n = 0;
     for(Scanner sc = new Scanner(f); sc.hasNext(); )
     {
        ++n;
        String line = sc.nextLine();
        if(rand.nextInt(n) == 0)
           result = line;         
     }

     return result;      
  }
}

这篇关于如何在Java中获取文本文件的随机行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆