使用Java从文件中的特定列中随机读取文本
我想从罗伯特,肖恩,约翰之间的column1中随机选择单个名称。使用Java从文件中的特定列中随机读取文本
例中的文件具有下列名称
Robert,Brian
Shawn,Bay
John,Paul
任何帮助将高度赞赏
FileInputStream objfile = new FileInputStream(System.getProperty("user.dir")+path);
in = new BufferedReader(new InputStreamReader(objfile));
String line = in.readLine();
while (line != null && !line.trim().isEmpty()) {
String eachRecord[]=line.trim().split(",");
Random rand = new Random();
//trying to randomly select text from specific row in a property file
sendKeys(firstName,rand.nextInt((eachRecord[0]));
line = in.readLine();
}
}
FileReader fr = new FileReader(path_of_your_file);
BufferedReader br = new BufferedReader(fr);
String sCurrentLine;
ArrayList<String> nameList=new ArrayList<String>(); //keep each first column entry inside this list.
while ((sCurrentLine = br.readLine()) != null) {
StringTokenizer st=new StringTokenizer(sCurrentLine, ",");
String name=st.nextToken();
nameList.add(name);
}
System.out.println(nameList.get((int)(Math.random()*nameList.size())));
//close file resources at finally block.
这不会编译。你可能意思是'random.nextInt(eachRecord.length)'......但即使这样也可能不会回答(目前不清楚)的问题,该问题旨在“从第一列中随机选择名称”。 – VGR
我编辑了我的问题。抱歉,所有的困惑。 – user2410266
@VGR编辑答案。 –
这得到一个随机名称从第1列到可变randomName
:
final int column = 1;
final String path = "file.ext";
Random rand = new Random();
List<String> lines = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
String randomName = lines.get(rand.nextInt(lines.size())).split(",")[column - 1];
你怎么样ct'eachRecord [0]'是一个整数吗? –
您需要定义“从特定行中随机选择文本”的含义。你对什么样的输入有什么样的输出? – pvg
感谢您的回复。我想从第一列中随机选择名称,如 Column1 Robert Shawn John – user2410266