简体   繁体   English

如何从Java中的文件读取随机行

[英]How to read a random line from a file in 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();
}
  1. This function is biased towards longer lines compared to shorter lines. 与较短的行相比,此功能偏向较长的行。
  2. This function is heavily biased against the first line. 此功能严重偏向第一行。 (This can be fixed. Think about it.) (可以解决。请考虑一下。)

I propose that you 1. first obtain the total number of lines in the file. 我建议您1.首先获取文件中的总行数。 Then 2. obtain a random number within that total. 然后2.在该总数中获得一个随机数。 Then 3. skip through the file to the point indicated by the random number. 然后3.跳过文件到随机数指示的位置。 Then 4. read the line of the file. 然后4.读取文件行。

If you want code I can supply some to get you started, but this should be fairly simple to implement. 如果您想要代码,我可以提供一些入门的方法,但是实现起来应该很简单。

as said you can use random to generate a number, 如前所述,您可以使用随机数生成数字,
but to read a new line search for it's index for "\\n" new line character 但要读取换行符以查找它的“ \\ n”换行符索引
and then seek(RANDOM) to that location and readLine() from that. 然后搜索(RANDOM)到该位置并从该位置读取Li​​ne()。

generate random number through Random . 通过Random生成随机数。 By that number you can read line from file. 通过该数字,您可以从文件中读取行。 You need to put some validation like that line already read or not etc. 您需要进行一些验证,例如该行是否已读取等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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