实现如下:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

public class RollCall {
    public static void main(String[] args) {
        BufferedReader reader = null;
        ArrayList<String> names = new ArrayList<String>();
        try {
            reader = new BufferedReader(new FileReader("name.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                names.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int index = new Random().nextInt(names.size());
        System.out.println("今天的点名结果是:" + names.get(index));
    }
}

注:本代码使用了try-with-resources的方式来自动释放资源,需要JDK1.7及以上版本支持


原文地址: https://www.cveoy.top/t/topic/fGhu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录