繁体   English   中英

使用Java从文件的特定列中随机读取文本

[英]Randomly read text from specific column in a file using 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();       

    }

}
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列获取一个随机名称到变量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];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM