读取一个名单,并随机生成三名幸运儿,将三名幸运儿存入新的文件中
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
//读取一个名单,并随机生成三名幸运儿,将三名幸运儿存入新的文件中
public class work {
public static void main(String[] args) {
//读取21级.txt文本文件
File fileName=new File("C:\\Users\\kobe\\Desktop\\test\\21级.txt");
Path path=fileName.toPath();
ArrayList<String> files=new ArrayList<String>();
try {
List<String> list= Files.readAllLines(path);
if (list!=null) {
for (String na : list) {
files.add(na);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(files);
//随机抽取三位不重复的幸运儿
try {
//set集合可以过滤掉重复值
HashSet<String> name=new HashSet<String>();
//使用Random类产生不重复的随机数
Random random=new Random();
//当存入set集合的幸运儿的人数不足三人时,会随机产生一个下标,再将随机下标的姓名存入set集合中
while (name.size()<3) {
int randomindex=random.nextInt(files.size());//随机下标的生成范围是在list集合中
String luckname=files.get(randomindex);
name.add(luckname);
}
System.out.println(name);
//将产生的幸运儿写入幸运儿的文件中
Files.write(Paths.get("C:\\Users\\kobe\\Desktop\\test\\音频文件\\幸运儿"), name, Charset.forName("UTF-8"),StandardOpenOption.CREATE_NEW);
} catch (Exception e) {
// TODO: handle exception
}
}
}