如何从Java中的文件读取随机行 [英] How to read a random line from a file in java
本文介绍了如何从Java中的文件读取随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我制作了一个程序,可以从文本文件中读取一行.我现在需要每次运行程序时使其读取一条随机行.这是我当前代码的一部分:
I've made a program that reads a line from a text file. i now need to make it read a random line each time the program is run. This is part of my current code :
if(Score<=5){
word = scan1 .nextLine();
System.out.println(word);
}
有没有简单的方法可以随机选择一条线?
Is there any simple way to pick a random line ?
推荐答案
public String getRandomLineFromTheFile(File file)
{
final RandomAccessFile f = new RandomAccessFile(file, "r");
final long randomLocation = (long) (Math.random() * f.length());
f.seek(randomLocation);
f.readLine();
return f.readLine();
}
- 与较短的行相比,此功能偏向较长的行.
- 此功能严重偏向第一行. (可以解决.请考虑一下.)
这篇关于如何从Java中的文件读取随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文