我试图让我的 android 应用程序从一个文本文件中读取并随机选择一个条目然后显示它,我该怎么做呢?我想我必须使用缓冲区读取器或输入流命令,但我不知道如何使用这些,我试过谷歌搜索但没有找到太多帮助。
据我所知(在一些帮助下)我必须读取文本文件,将其添加到字符串中?并使用以下命令随机选择一个条目
Random.nextInt(String[].length-1).
我该怎么做? :\我对所有这些缓冲区读取器等东西都很陌生。
最佳答案
您在这里询问 2 种不同的操作。不要将它们混为一谈,从而混淆了问题。您想知道如何:
- 将磁盘中的文件读入一组字符串。
从一组字符串中随机选择一个字符串。
// Read in the file into a list of strings BufferedReader reader = new BufferedReader(new FileReader("inputfile.txt")); List<String> lines = new ArrayList<String>(); String line = reader.readLine(); while( line != null ) { lines.add(line); line = reader.readLine(); } // Choose a random one from the list Random r = new Random(); String randomString = lines.get(r.nextInt(lines.size()));
关于java - 从文件中读取并显示随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6599678/