简体   繁体   English

随机读取文本文件

[英]Reading from a text file Randomly

I just began developing android apps and i suddenly found it difficult reading a word from a text file, randomly,when a button is clicked.i tried putting all the words from the text file into an array and told it to display the word until the next line( randomly), but it doesn't seem to work. 我刚开始开发android应用,突然发现当单击按钮时,很难从文本文件中读取单词。我尝试将文本文件中的所有单词放入数组,并告诉它显示单词直到下一行(随机),但似乎不起作用。 I want to know how to read and display words from a text file one by one and Randomly, every time a button is clicked !!! 我想知道每次单击一个按钮时,如何一次又一次地随机读取和显示文本文件中的单词!!!

您应该尝试逐字分割文本并将其放入数组中。

Create one big string by reading the file to the end. 通过读取文件到末尾来创建一个大字符串。 Split the big string into an arraylist by using string.split and give the split method the correct split parameter (" " or ","). 使用string.split将大字符串拆分为一个数组列表,并为split方法提供正确的split参数(“”或“,”)。 Take a random entry out of the arraylist, where the maximum allowed random is the size of the arralist. 从arraylist中取出一个随机条目,其中允许的最大随机数是arralist的大小。

Sample code for displaying a word from an array of words. 用于显示单词数组中的单词的示例代码。

Functions of most lines are written in comment. 大多数行的功能以注释形式编写。

string words[]; // array for words.
   /* code for reading text from text file and place words in text into words[] */
int sizeOfArray = numberOfWordsInArray; /* the value is set in the code of words placing into array */

Random rnd = new Random(); // random number generator

int index = rnd.nextInt(sizeOfArray); // nextInt returns random integer number between 0 and (sizeOfArray-1).

printf("%s\n",words[index]); // select a word by random number and display it.

I guess you have one word per line. 我想你每行一个字。 Use code below to read file and save it into list. 使用下面的代码读取文件并将其保存到列表中。

    ArrayList<String> list = new ArrayList<String>();
try {
    InputStream instream = openFileInput("yourfile.txt");
    if (instream) {
        BufferedReader buffreader = new BufferedReader(new InputStreamReader(instream));
        String line;
        while (( line = buffreader.readLine())) {
        list.add(line);
    }
}
instream.close();
} catch (java.io.FileNotFoundException e) {
} 

Place above code inside onCreate method. 将上面的代码放在onCreate方法中。 Now use import java.util.Random to randomly select your item from list. 现在使用import java.util.Random从列表中随机选择您的项目。 Place below code inside OnClickListener. 将以下代码放在OnClickListener中。

public Item anyItem() 
    {   private Random randomGenerator = new Random();
        int index = randomGenerator.nextInt(list.size());
        Item item = list.get(index);
        System.out.println("Your Selected item is " + item");
        return item;
    }

Now you can do anything with the item returned from above anyItem() method, hoped it helped you. 现在,您可以对anyItem()方法上方返回的项目进行任何操作,希望对您有所帮助。

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

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