Was*_*sif 3 java io file-io android
我试图让我的Android应用程序从文本文件中读取并随机选择一个条目然后显示它,我该怎么做呢?我想我必须使用缓冲读取器或输入流命令,但我不知道如何使用这些,我已经尝试谷歌搜索但没有找到很多帮助.
据我所知(并提供一些帮助),我必须阅读文本文件,将其添加到字符串中?并使用以下命令随机选择一个条目
Random.nextInt(String[].length-1).
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?:\ im对所有这些bufferreader的东西都很新.
你在这里问两个不同的操作.不要把问题弄糊涂在一起弄乱问题.你想知道如何:
从一组字符串中随机选择1个字符串.
// 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()));
Run Code Online (Sandbox Code Playgroud)