您的位置:首页 > 其它

随机读取txt文件的某一行

2015-10-26 13:00 351 查看
随机读取txt文件的某一行,每一行的概率都是一样的

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();
System.out.println("n: "+n+" line: "+line);
if(rand.nextInt(n) == 0)
result = line;
}

return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: