代码:

/*
    获取随机文件文字
     */
    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;
    }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-31
  • 2021-08-18
  • 2021-06-11
  • 2022-12-23
  • 2021-09-30
  • 2022-12-23
猜你喜欢
  • 2021-05-11
  • 2022-12-23
  • 2021-12-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-30
相关资源
相似解决方案