- package cn.itcast.random;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.Random;
- public class StartRandom {
- static boolean flag = true;
- public static void main(String[] args) throws Exception {
- start();
- }
- public static void start() throws Exception
- {
- FileWriter fw = new FileWriter("names.txt", true);
- BufferedWriter bw = new BufferedWriter(fw);
-
-
- String[] strArr = readNames("names.txt");
- Random rd = new Random();
- int rdNo = rd.nextInt(strArr.length) + 1;
- for (int i = 0; i < rdNo; i++) {
- getRandomName(strArr);
- }
- }
-
- /**
- * 读取姓名并转化为数组
- */
- public static String[] readNames(String path) throws Exception
- {
- FileReader fis = new FileReader(path);
- BufferedReader br = new BufferedReader(fis);
- String line = null;
- StringBuilder sb = new StringBuilder();
- while((line = br.readLine()) != null)
- {
- sb.append(line);
- }
- String[] strArr = sb.toString().split(" ");
- return strArr;
- }
-
- /**
- * 打印随机名字
- */
- public static void getRandomName(String[] arr)
- {
- Random rd = new Random();
- int num = 0;
-
- // System.out.println(flag);
- num = rd.nextInt(arr.length);
- System.out.println(arr[num]);
- }
-
- }
复制代码
|
|