使用Java

时间:2017-09-14 15:59:17

标签: java

我想从Robert,Shawn,John之间的column1中随机选择一个名字。

示例文件具有以下名称

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();       

    }

}

2 个答案:

答案 0 :(得分:0)

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.

答案 1 :(得分:0)

这会将第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];