Scanner s=new Scanner(new File("e:/names.txt")); int count=0; while(s.hasNext()) { System.out.println(s.nextLine()); count++;} Random r=new Random(); int index=r.nextInt(count+1); while(index==0) { index=r.nextInt(count+1); } String aa=String.valueOf(index); System.out.println("========="); s=new Scanner(new File("e:/names.txt")); while(s.hasNext()) { String line=s.nextLine(); if(line.contains(aa)) { String name=line.split("\\.")[1]; System.out.println(name); break; } }