Java 从txt文件中的specefic行提取字符串

Java 从txt文件中的specefic行提取字符串,java,Java,我是一个java初学者,我有一个小问题,希望你们能帮我解决。 我有一个Names.txt文件,其中包含大量随机名称,每行都有一个合适的名称 (解释: 约翰 迈克尔 安东尼 等等……) 我一直在编写一个函数,随机选择以下名称之一: public static void RandomNameGenerator() throws FileNotFoundException { // the File.txt has organized names, meaning that each line

我是一个java初学者,我有一个小问题,希望你们能帮我解决。 我有一个Names.txt文件,其中包含大量随机名称,每行都有一个合适的名称 (解释: 约翰 迈克尔 安东尼 等等……) 我一直在编写一个函数,随机选择以下名称之一:

public static void RandomNameGenerator() throws FileNotFoundException
{
    // the File.txt has organized names, meaning that each line contains a name
    //the idea here is to get a random int take that number and find a name corresponding to that line number
    int txtnumlines = 0; // how many lines the txt file has
    Random random = new Random();
    Scanner file = new Scanner(new File("Names.txt")); //loads the txt file
    while (file.hasNext()) //counts the number of lines
    {
        file.nextLine();
        txtnumlines += 1;
    }
    int randomintname = random.nextInt(txtnumlines);
    // takes a random number, that number will be used to get the name from the txt line
    String RandomName = "";

    // I'm stuck here :(
}
问题是我不知道如何继续,更具体地说,如何使用表示随机线的随机整数提取该名称(比如alex)

Random random = new Random();
String randomLine = lines[random.nextInt(lines.length)].trim();
希望我的问题很清楚,
谢谢你帮助我

在这里,您可能想尝试以下方法:

public static void RandomNameGenerator() throws FileNotFoundException
{
    // the File.txt has organized names, meaning that each line contains a name
    //the idea here is to get a random int take that number and find a name corresponding to that line number
    int txtnumlines = 0; // how many lines the txt file has
    Random random = new Random();
    Scanner file = new Scanner(new File("Names.txt")); //loads the txt file
    Scanner fileReloaded = new Scanner(new File("Names.txt")); //Let's use another one since we can't reset the first scanner once the lines have been counted (I'm not sure tho)
    while (file.hasNext()) //counts the number of lines
    {
        file.nextLine();
        txtnumlines += 1;
    }
    int randomintname = random.nextInt(txtnumlines);
    // takes a random number, that number will be used to get the name from the txt line

    int i = 0;
    String RandomName = "";
    while(fileReloaded.hasNext())
    {
        String aLine = fileReloaded.nextLine();
        if (i == randomintname) Randomname = aLine;
        i++;
    }

    // Now you can do whatever you want with the Randomname variable. You might want to lowercase the first letter, however. :p
}
读所有行

String[] lines = new Scanner(
    MyClass.class.getClassLoader().getResourceAsStream("Names.txt"),
    StandardCharsets.UTF_8.name()
).next().split("\\A");
提取随机线

Random random = new Random();
String randomLine = lines[random.nextInt(lines.length)].trim();

这回答了你的问题吗?具体来说,答案是最多的,不是公认的答案谢谢你,阿蒙加伦先生,它现在起作用了:)谢谢,先生,我厌倦了类似的方法,但由于缺乏经验,它是徒劳的