实现步骤
- 【第一步】 读取文本每行,转换为List集合
- 【第二步】 根据提取数量,随机选取不重复的几行数据
- 【第三步】 提取结果
代码实现
/** * @Title: 提取文本 * @MethodName: abstractTxt * @param txt * @param abstractNum * @Return void * @Exception * @Description: * * @author: 王延飞 * @date: 2019/10/5 21:47 */ public static void abstractTxt(String txt,int abstractNum) throws Exception{ // 【第一步】文本每行,转换为List集合 //新建一个字符缓冲输入流对象,将基本字符输入流作为其参数,将e.txt文件作为基本字符输入流参数,其为需要读取的文本文件 BufferedReader br = new BufferedReader(new FileReader(txt)); //定义字符串变量str String str; //新建一个ArrayList集合,用其父类给ls集合定义数据类型 List<String> list = new ArrayList<String>(); //将br输入流对象赋值给字符串变量,判断其是否为空 while((str=br.readLine())!=null) { //若不为空,则将字符串str添加至集合ls中 list.add(str); } // 【第二步】 根据提取数量,随机选取不重复的几行数据 //文本数量 int n = list.size(); System.out.println("文本数量"+n); // 文本的行号-1 int[] numbers = new int[n]; for(int i = 0; i<numbers.length; i++){ numbers[i] =i; } // 提取数量,构建随机不重复的数 int[] result = new int[abstractNum]; for (int i = 0; i < result.length; i++) { int r = (int)(Math.random() * n); result[i] = numbers[r]; /*防止重复,去掉已经提取过的*/ numbers[r] = numbers[n-1]; n--; } // 【第三步】 提取结果 //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("../../user/output.txt")),"utf-8")); BufferedWriter bw = new BufferedWriter(new FileWriter(new File("D:\\user\\output.txt"))); for(int i:result){ System.out.println("坐标:"+i); String string = list.get(i); bw.write(string); bw.newLine(); } bw.flush(); bw.close(); //关闭字符缓冲输入流 br.close(); } public static void main(String[] args) throws Exception { abstractTxt("D:\\user\\input.txt", 10); }