如何从txt文件中选择一个随机单词?

时间:2016-10-09 01:36:00

标签: java file

我有一个方法需要从txt文件中选择一个随机单词,但它只在某些时候起作用。

该文件的内容如下:

Broccoli
Tomato
Kiwi
Kale
Tomatillo

我的代码:

import java.util.Random; 
import java.util.Scanner; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException;

public String getRandomItem(){
    Scanner fileIn = null;

    String temp = ""; 
    int r = randomGenerator.nextInt(5) + 1; 
    byte i = 0;

    try {
        fileIn = new Scanner(new FileInputStream("bundles.txt"));
    } catch (FileNotFoundException e) {
        System.out.println("File not found.");
        System.exit(0);
    } 

    while(i <= 5){
        temp = fileIn.nextLine();

        if(i == r){ 
            break;  
        }

        i++;
    }

    fileIn.close();

    return temp; 
}

有人可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:2)

我会使用Files.readAllLines(Path)一次读取所有行,然后从中获取一个随机单词。像,

private static List<String> lines = null;
static {
    try {
        lines = Files.readAllLines(new File("bundles.txt").toPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private Random rand = new Random();

public String getRandomItem() {
    return lines.get(rand.nextInt(lines.size()));
}