延迟读取Android中的.txt文件

问题描述 投票:0回答:1

我是Android Studio的初学者,我当前的项目从.txt文件中读取单词(基本上是字典),并向用户输出随机单词。用户依次输入另一个单词,该单词的一个字符与显示给他的字符不同。一切工作正常,除了当我打开读取另一个.txt文件(在这种情况下为另一种语言的词典)时,该程序会降低从该文件中读取所有这些单词的速度。我基本上将所有单词读一次,然后将它们添加到字符串数组列表中,以便以后使用。在这一点上,我不知道这种暂时滞后的问题根源是什么,因为每个.txt文件中最多有1-2 000个单词,而且我认为电话的速度足以一次读取它们。反正对此一无所知。我知道可以使用.sql替代.txt更好的替代方法,但我现在很熟悉读取.txt文件,并且现在希望对此进行处理。有人可以推荐我一些方法来解决这种短暂的延迟吗?先感谢您。这是我的代码,更改语言后会调用这两个方法:

public void restartGame() throws IOException {
    //availableWords is the list of all words
    availableWords = new ArrayList<>();
    //currentStream is an InputStream targeted to the current .txt file
    currentStream.reset();
    //I read all the words and add them to the arraylist
    Scanner reader = new Scanner(currentStream);
    while (reader.hasNext())
        availableWords.add(reader.next());

    //I choose a random word from the arraylist to begin with
    String chosenWord = availableWords.get((int) (availableWords.size() * Math.random()));
    wordOutput.setText(chosenWord);
    availableWords.remove(chosenWord);
    String previousText = "";
    for( int i = 0; i < 4; i++) {
        for (int chars = 0; chars < currentWordLength; chars++)
            previousText += " ";
        previousText += "\n";
    }
    previousWords.setText(previousText);
    wordInput.setText("");

    restartButton.setVisibility(View.GONE);
    wordInput.setVisibility(View.VISIBLE);
    enterButton.setVisibility(View.VISIBLE);
}

    //a spinner to let user select a language
    languageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            //chosen language is assigned to a variable
            currentLanguage = parent.getSelectedItem().toString();
            //corresponding inputStream is assigned to currentStream so that in restartGame method, the game restarts with the chosen language
            ArrayList<InputStream> wordLengthLanguage = wordsFile.get(currentWordLength - 3);
            currentStream = wordLengthLanguage.get(languages.indexOf(currentLanguage));
            try {
                restartGame();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
android android-studio text-files readfile
1个回答
0
投票

从文件中读取单词的目的或目标是什么?如果要保留数据(作为sqlite),则可以创建一个包含字符串数组的String资源。每次启动应用程序时,您都可以从资源中读取它们。

[首先,转到android studio上的应用程序文件夹,然后res > values右键单击值,然后单击new > values resource file。根据需要命名。在资源标签中创建如下所示:

<string-array name="words">
    <item>Word 1</item>
    <item>Word 2</item>
</string-array>

当需要数组时,只需执行以下操作:

getResources().getStringArray(R.array.words)

其中“单词”是字符串数组的名称。请注意,如果您在一个片段上,则需要上下文来访问资源。

此数组不可编辑,因此您不能在执行时添加更多单词,所有单词必须先创建后才能放入资源文件。

希望它对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.