代码:
/*
获取随机文件文字
*/
public static String random(String path) {//路径
String name = null;
try {
//把文本文件中的数据存储到集合中
BufferedReader reader = new BufferedReader(new FileReader(path));
//定义集合数组
ArrayList<String> list = new ArrayList<String>();
String line = null;
while ((line = reader.readLine()) != null) {
list.add(line);//把每一行讀取到的值存储在集合中
}
reader.close();
//随机产生一个索引
Random random = new Random();
int index = random.nextInt(list.size());//产生的索引值的大小在0-size之间
//根据该索引获取一个值
name = list.get(index);
} catch (Exception e) {
e.printStackTrace();
}
return name;
}